我們在用 Python Turtle The library has some fun drawing different shapes,But we can make the function to draw these shapes more interesting by adding variables to the program.例如,By using a variable when drawing a square,We can control how far the turtle moves as it draws lines for each side of the square.這樣,我們可以使用一個函數,by using variables,We can draw any size square we like.Now let's see how to do this.
這個新的 draw_square() Functions now have a name called length 的新[變量]
def draw_square(length):
for i in range(4):
forward(length)
left(90)
復制代碼
這使得在調用 draw_square() A value can be passed to the function,This allows each side to move forward by this amount when drawing the square.我們可以通過調用 draw_square() 並傳入 75 來測試這一點,This will make the turtle move 75 像素.
from turtle import *
drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('arrow')
def draw_square(length):
for i in range(4):
forward(length)
left(90)
draw_square(75)
done()
復制代碼
Now there is the use of variables,We can easily draw squares of different sizes.Let's test drawing one on each side150像素的正方形.
draw_square(150)
復制代碼
Using a variable when defining a function makes the function more flexible,Because the output of the function can be changed,without having to update the function itself every time.
如果在調用 draw_square() The function does not pass in the value of the length variable,我們將得到一個錯誤.
Traceback (most recent call last):
File "C:\python\justhacking\testing.py", line 14, in <module>
draw_square()
TypeError: draw_square() missing 1 required positional argument: 'length'
復制代碼
To avoid this possible error condition,讓我們重新定義 draw_square() 函數,and use it without providing a default value.We'll set the default to like this90.
from turtle import *
drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('arrow')
def draw_square(length=90):
for i in range(4):
forward(length)
left(90)
draw_square()
done()
復制代碼
現在,當draw_square()被調用時,不會顯示錯誤,The program just defaults to drawing a length of each side90像素的正方形.The following program calls draw_square() 函數 3 次.No variable is passed at a time,There are two different numeric values twice.
from turtle import *
drawing_area = Screen()
drawing_area.setup(width=750, height=500)
shape('arrow')
def draw_square(length=90):
for i in range(4):
forward(length)
left(90)
draw_square()
draw_square(150)
draw_square(200)
done()
復制代碼
The result is three squares of different sizes.