UnboundLocalError和type

2024-09-29 22:12:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个初学者。我的错误是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()

Tags: ofthetonumberinputdefbeint
1条回答
网友
1楼 · 发布于 2024-09-29 22:12:15

似乎您误用了方法变量。您正在将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)。你知道吗

相关问题 更多 >

    热门问题