在python中使用turtle模型
使用元组列表实现循环
import turtle
alex = turtle.Turtle()
alex.shape("turtle")
for i in [0,1,2,3,4]:
alex.forward(100)
alex.left(72)
for aColor in ["red","blue","yellow","green","purple"]:
alex.color(aColor)
alex.forward(100)
alex.left(72)
这里代码的意思是:每当i与元组中的值相匹配,for循环的部分将会重复forward和left的动作,i从0开始自动加1(一定要从0开始,而不是1)
使用Range函数实现循环(range函数相当于自建元组)
import turtle
alex = turtle.Turtle()
alex.shape("turtle")
for i in range(5):
alex.forward(100)
alex.left(72)
for aColor in ["red","blue","yellow","green","purple"]:
alex.color(aColor)
alex.forward(100)
alex.left(72)
最终呈现
Paste_Image.png特别的,可以将python turtle module的指令混合 使用 比如下面的螺旋线
import turtle
alex = turtle.Turtle()
alex.color("darkgreen")
alex.pensize(5)
alex.shape("turtle")
print(range(5,100,2))
for size in range(5,100,2):
alex.forward(size)
alex.left(25)
Paste_Image.png
import turtle
alex = turtle.Turtle()
alex.color("brown")
alex.shape("turtle")
print (range(5,100,2))
alex.penup()
for size in range (5,100,2):
alex.stamp()
alex.forward(size)
alex.left(25)
其中alex.stamp()表示让小乌龟在屏幕上留下移动印记
Paste_Image.pngPython中range的用法
函数原型:range(start, end, scan):
参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
end:技术到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
示例
range(5) #代表从0到5(不包含5)
[0, 1, 2, 3, 4]
range(0,5) #代表从0到5(不包含5)
[0, 1, 2, 3, 4]
range(1,5) #代表从1到5(不包含5)
[1, 2, 3, 4]
range(1,5,2) #代表从1到5,间隔2(不包含5)
[1, 3]
Python Turtle指令官方手册
https://docs.python.org/2/library/turtle.html
网友评论