我正在尝试编写一些代码,以在turtle模块中打印一些形状。这是我的代码:
#imports
`import random`
#The functions that are used later.
shape = turtle.Pen()
def spiraling_shapes():
for spiral in range(1,2):
shape.forward(20)
shape.left(shape_sides)
def rotating_shapes():
for rotating in range(1,2):
shape.left(20)
for shape_image in range(1,2):
shape.forward(50)
shape.left(shape_sides)
#First loop. This will generate a random number
for shape in range (1,6):
number_of_sides = random.randint(3,8)
shape_sides = 360 / number_of_sides
#This will check if it is even or odd and run the correct function accordingly
if number_of_sides % 2 == 0:
spiraling_shapes()
else:
rotating_shapes()
''' 它保持运行状态。forward(20) AttributeError:“ int”对象没有属性“ forward”
答案 0 :(得分:2)
您需要小心使用全局变量,因为很容易意外覆盖或修改它们,从而导致难以解决的错误。这就是为什么您会看到人们避免这样做或在所有大写字母中为常量命名的原因。
您在这里使用shape
shape = turtle.Pen()
但是,您稍后将其重新分配:
for shape in range (1,6):
因此,形状现在是整数,而不是Pen,并且会导致您调用Pen.forward()
方法的错误。
尝试重命名您的变量之一以快速修复。