程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to use variables in Python Turtle

編輯:Python

我們在用 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() 中加入一個變量

這個新的 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()
復制代碼


Draw squares of different sizes

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.


Set a default length

如果在調用 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.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved