UnboundLocalError和TypeError

时间:2014-11-09 21:16:00

标签: python turtle-graphics

我是初学者。我的错误是UnboundLocalError: local variable 'n' referenced before assignment。我找了答案,但我不理解大部分代码。

def numberOfSquares(n):#This is where I get the user input.
    n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
    while n < 0:
        print("Please try another number.")
        n= int(input("Please input a number higher than 1 to be the number of squares drawn."))
    print("Thanks for your contribution!")

def main():# I call the other function in this one, and draw n number of squares. I have not even put #the different colors on it yet.   
    numberOfSquares(n)
    import turtle
    for i in range(n):
        turtle.circle(40,steps= 4)
        turtle.left(45)
        turtle.forward(50)
        n-=1
    turtle.write("Colors of the Rain")

main()

1 个答案:

答案 0 :(得分:0)

您似乎在滥用方法变量。您正在将n传递给numberOfSquares,而您确实希望获得返回值。

def number_of_squares():
    # Your code here, and finally
    return n

然后在main()

n = number_of_squares()

关于第二个错误,你有一个错字。方法turtle.cicrle接收steps参数而不是step

turtle.circle(40, steps=4)

最后,python中有一个强大的命名约定。所有方法都应该是小写的,带有number_of_squares等下划线,而不是驼峰式(numberOfSquares)。