如何修复此错误消息?

2024-10-02 00:37:39 发布

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

myVar = int(input("What do you want to start out with? "))
mySubtactor = int(input("What do you want to be the subtracter? "))


def function():
    choice = input("Do you want to take away? Please say yes or no. ")
    if(choice == 'yes'):
        print(myVar)
        myVar = myVar - mySubtactor
        function()
    if(choice == 'no'):
        print("You have decided not to subtract. Your number is still " + myVar)
        function()
function()

我不断收到这个错误信息:

File "C:\Users\Name\Desktop\new 3.py", line 8, in function print(myVar) UnboundLocalError: local variable 'myVar referenced before assignment

我很抱歉,如果这是一个noob的问题,但我不知道我做错了什么。你知道吗


Tags: tonoyouinputiffunctiondowhat
3条回答

试试这个:

def function():
  global myvar
  ... 

可以使用myvar而不声明global(只需访问myvar变量),但在函数中分配了它,因此需要使用global。你知道吗

另请参见:

我认为这是因为您需要将myVar和mySubtractor传递给您的函数,或者全局调用它们,甚至使用函数设置它们

您可能想了解Python中的作用域和名称空间:https://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces。你知道吗

function()中引用myVar。Python首先查看function()的局部范围,然后再查看全局范围。由于在函数中赋值给myVar,解释器决定这是一个局部变量,而不是使用全局变量。但是,如错误消息中所述,在分配给它之前引用myVar。你知道吗

如果未在函数中赋值,则可以使用全局变量而不声明它global

myVar = 'hello'

def test():
    print myVar

test()
#hello

但如果在函数中赋值给myVar,则将使用局部变量:

myVar = 'hello'

def test():
    myVar = 'Goodbye'
    print myVar

test()
#Goodbye
print myVar
#hello

但是,如您所知,如果您在函数中赋值给myVar,但在此之前引用它,您将得到一个错误:

myVar = 'hello'

def test():
    print myVar
    myVar = 'Goodbye'

test()
#UnboundLocalError: local variable 'myVar' referenced before assignment

要解决此问题,可以声明myVar全局:

def function():
    global myVar
    ...

或者将变量传递给函数:

def function(myVar):
    ...

相关问题 更多 >

    热门问题