我看到的第一个问题是你在前锋线上留下了一个“r”。t.forwad(length)
应该是t.forward(length)
另外,如果使用input()width和length将是字符串,但它们需要进行类型转换。Specifically,长度必须是整数或浮点数,宽度必须是正整数。length = None
while not length:
try:
length = float(input('Enter your preferred turtle line length: '))
except ValueError:
print('You need to enter a number')
width = None
while not width:
try:
width = int(input('Enter your preferred turtle line width: '))
except ValueError:
print('You need to enter a positive integer')
else:
if width < 1:
print('You need to enter a positive integer')
width = None
我这里的代码将使用循环从用户那里获得正确的输入。它将尝试拒绝错误的输入。例如,如果用户在询问长度时键入“pumpkin”。
类似地,我捕获长度和宽度条目问题的方式,您将希望捕获形状和颜色的用户条目问题。确保用户输入有效的颜色。确保形状在允许的形状列表中。
最后一个问题是这里的代码缩进不正确。您需要在if:和else:子句之后缩进。
下面是整个程序的工作原理:import turtle
s = turtle.Screen()
t = turtle.Turtle()
length = None
while not length:
try:
length = float(input('Enter your preferred turtle line length: '))
except ValueError:
print('You need to enter a number')
width = None
while not width:
try:
width = int(input('Enter your preferred turtle line width: '))
except ValueError:
print('You need to enter a positive integer')
else:
if width < 1:
print('You need to enter a positive integer')
width = None
color = None
while not color:
color = input('Enter your preferred turtle line color: ')
try:
t.pencolor(color)
except:
print('You need to enter a color that I know.')
color = None
shape = None
while not shape:
shape = input('Specify whether you want to draw a line, triangle, or square: ')
if shape.lower() not in ['line', 'triangle', 'square']:
shape = None
print('I only draw lines, triangles and squares!')
t.pensize(width)
if shape.lower() == 'line':
t.forward(length)
elif shape.lower() == 'triangle':
t.forward(length)
t.right(120)
t.forward(length)
t.right(120)
t.forward(length)
else:
t.forward(length)
t.right(90)
t.forward(length)
t.right(90)
t.forward(length)
t.right(90)
t.forward(length)
s.exitonclick()
注意,我也修正了三角形。。。