构建自己的循环
内建函数range(n):构建一个0到n-1的整数数字列表
class range
(stop)
class range
(start, stop[, step])
内建函数list():构建列表
for语句:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]
用for循环生成四个花瓣
# Rosette4.py
import turtle
t = turtle.Pen()
for x in range(4):
t.circle(100)
t.left(90)
用for循环生成六个花瓣
# Rosette6.py
import turtle
t = turtle.Pen()
for x in range(6):
t.circle(100)
t.left(60)
增加用户输入功能
获取输入的数字字符串:turtle.
numinput
(title, prompt, default=None, minval=None, maxval=None)
# RosetteGoneWild.py
import turtle
t = turtle.Turtle()
# 询问用户需要画几个花瓣,默认画6个花瓣
number_of_circles = int(turtle.numinput("花瓣数量:","多少个花瓣?", 6))
for x in range(number_of_circles):
t.circle(100)
t.left(360/number_of_circles)
游戏循环和while循环
while语句:适合循环次数不确定的情况
while_stmt ::= "while" assignment_expression ":" suite ["else" ":" suite]
# SayOurNames.py - 在屏幕上打印人名
# 询问用户想要输入哪个人的名字
name = input("输入某个人的名字? ")
# 一直打印名字直到用户想退出
while name != "":
# 输出名字100次
for x in range(100):
# 打印名字后再打印一个空格
print(name, end = " ")
print() # 打印100次名字后,空一行
# 询问另一人的名字或者退出程序
name = input("输入另一个人的名字, 或者按 [ENTER]键 退出: ")
print("游戏结束,谢谢你玩这个游戏!")
家庭成员螺旋线
# SpiralFamily.py - prints a colorful spiral of names
import turtle
t = turtle.Turtle()
turtle.bgcolor("black") # 设置窗口的背景色
colors = ["red", "yellow", "blue", "green", "orange",
"purple", "white", "brown", "gray", "pink" ]
family = [] # 设置一个用于存储家庭成员姓名的空列表
# 要求用户输入第一个名字
name = turtle.textinput("我的家庭",
"输入一个名字, 或者按 [ENTER]键 退出:")
# 一直询问用户
while name != "":
# 添加名字到family列表
family.append(name)
# 询问另一个名字或者退出
name = turtle.textinput("我的家庭",
"输入一个名字, 或者按 [ENTER]键 退出:")
# 画出由这些名字构成的螺旋线
for x in range(100):
t.pencolor(colors[x%len(family)]) # 通过颜色列表来轮换画笔的颜色
t.penup() # 不要画常规的螺旋线
t.forward(x*4) # 移动海龟
t.pendown() # 准备画名字,名字也轮换的
t.write(family[x%len(family)], font = ("Arial", int((x+4)/4), "bold") )
t.left(360/len(family) + 2) # 海龟左转
整合-由螺旋线构成风扇叶子
# ViralSpiral.py - 由螺旋线构成风扇叶子!
import turtle
t = turtle.Turtle()
t.penup()
turtle.bgcolor("black")
# 风扇叶子默认是4片,最少2片,最多6片
sides = int(turtle.numinput("风扇叶子数量",
"风扇叶子数量? (2-6)", 4,2,6))
colors = ["red", "yellow", "blue", "green", "purple", "orange"]
# 外部循环确定每条螺旋线的起始位置
for m in range(100):
t.forward(m*4)
position = t.position() # Remember this corner of the spiral
heading = t.heading() # Remember the direction we were heading
print(position, heading)
# 内部循环制作螺旋线
# Draws a little spiral at each corner of the big spiral
for n in range(int(m/2)):
t.pendown()
t.pencolor(colors[n%sides])
t.forward(2*n)
t.right(360/sides - 2)
t.penup()
t.setx(position[0]) # Go back to the big spiral's x location
t.sety(position[1]) # Go back to the big spiral's y location
t.setheading(heading) # Point in the big spiral's heading
t.left(360/sides + 2) # Aim at the next point on the big spiral
编程挑战
螺旋线玫瑰花瓣
修改病毒式的螺旋线程序,将小的螺旋线替换为玫瑰花瓣,运行结果如下图