Python Zero Basic Quick Start Fun Tutorial (Dr. Mi's Turtle Drawing Turtle) 2. Variables



Everyone has learned the concept of variables in high school. For example: we set x = 100, then we can deduce x*2 = 200

Try the following PYTHON code

 

  1 import turtle



3 turtle.shape("turtle")

4 x = 100

5 turtle.forward(x)

6 turtle .left(45)

7 turtle.forward(2*x)



9 turtle.exitonclick()

 

Run the above code, the little turtle will draw the following pattern

 

x = 100 Declare the variable x and assign it to 100, use In the familiar middle school mathematics language, it is "let x equal to 100".

In the following code, turtle.forward(x) is to let the turtle move forward x units. Since x has been assigned to 100, it is actually Forward the turtle a distance of 100 units (the shorter horizontal line in the image)

Similarly turtle.forward(2*x) is to advance the turtle 2 times the distance of x units, which is 2 times the distance of 100 units distance, eventually the turtle will crawl forward a distance of 2 x 100 = 200 units (the long slash in the image pointing to the upper right)

[Hint]

PYTHON (and most programming languages) use * for mathematical multiplication operation to avoid confusion with the letter x

Unlike middle school math, variables in PYTHON can be used to represent not only numbers, but all kinds of non-numeric things. For example, with ipaomi = turtle you can turn Dr. Mi into a turtle, and then you can use the ipaomi variable to control the turtle's drawing.

The following code, the drawn image is the same as before, the difference is that we assign a turtle to the variable ipaomi

 

   1 import turtle



3 ipaomi = turtle

4 ipaomi.shape("turtle")

5 x = 100

6 ipaomi.forward(x)

7 ipaomi.left(45)

8 ipaomi.forward(2*x)



10 ipaomi.exitonclick()

 

[Exercise]

PYTHON-beginners/en/_images/house.png" alt="_images /house.png" />

Try to draw a house (use variables to complete, try to adjust the value of variables, draw houses of different sizes)

[Hint]

You may need to use the operation of opening the square root, introduce the math module, Then use the sqrt method of the math module to perform the square root operation.

  For example, the following code computes the square root of 5 and assigns the result to the variable x

 

  1 import math



3 x = math.sqrt(5)

 

[Original link] PYTHON-%E9%9B%B6%E5%9F%BA%E7%A1%80-%E5%BF%AB%E9%80%9F%E5% 85%A5%E9%97%A8-%E8%B6%A3%E5%91%B3%E6%95%99%E7%A8%8B-%E5%92%AA%E5%8D%9A%E5% A3%AB-%E6%B5%B7%E9%BE%9F%E7%BB%98%E5%9B%BE-turtle-2-%E5%8F%98/" target="_blank"> http://www.ipaomi.com/2017/11/15/PYTHON-zero base-quick start-fun tutorial-dr.mi-turtle drawing-turtle-2-change/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326390581&siteId=291194637