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的问题,但我不知道我做错了什么。你知道吗
试试这个:
可以使用
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
,则将使用局部变量:但是,如您所知,如果您在函数中赋值给
myVar
,但在此之前引用它,您将得到一个错误:要解决此问题,可以声明
myVar
全局:或者将变量传递给函数:
相关问题 更多 >
编程相关推荐