如何修复此错误消息?

时间:2014-04-14 01:35:14

标签: python loops subtraction

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()

我继续收到此错误消息:

  

文件" C:\ Users \ Name \ Desktop \ new 3.py",第8行,在函数print(myVar)中   UnboundLocalError:在赋值之前引用的局部变量' myVar

对不起,如果这是一个菜鸟问题,但我不知道自己做错了什么。

3 个答案:

答案 0 :(得分:1)

您可能希望阅读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):
    ...

答案 1 :(得分:0)

试试这个:

def function():
  global myvar
  ... 

您可以使用myvar而无需声明global(只需访问myvar变量),但在您分配的功能中,您需要使用global

另见:

答案 2 :(得分:0)

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