Python 如何绕过UnboundLocalError?
我刚开始编程,试图写些东西,但(当然)失败了。之后,我找到了真正的问题:Python 如何绕过UnboundLocalError?,python,Python,我刚开始编程,试图写些东西,但(当然)失败了。之后,我找到了真正的问题:UnboundLocalError。为了把你从周围的废墟中解救出来,我将代码简化为: def test(): try: i1 = int(i1) i2 = int(i2) except ValueError: print "you failed in typing a number" def input(): i1 = raw_input('plea
UnboundLocalError
。为了把你从周围的废墟中解救出来,我将代码简化为:
def test():
try:
i1 = int(i1)
i2 = int(i2)
except ValueError:
print "you failed in typing a number"
def input():
i1 = raw_input('please type a number \n >')
i2 = raw_input('please type a number \n >')
然后我写下:
>>>input()
please insert a number
> 3
please insert a number
> 2
>>>test()
然后我得到:
that was not a number
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in test
UnboundLocalError: local variable 'i1' referenced before assignment
那不是一个数字
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第7行,在测试中
UnboundLocalError:赋值前引用的局部变量“i1”
我怎样才能用Pythonic的方式解决这个问题?或者我应该采取完全不同的方法吗?最标准的方法是为测试方法提供参数:
def test(i1, i2):
try:
i1 = int(i1)
i2 = int(i2)
except ValueError:
print "you failed in typing a number"
def input():
i1 = raw_input('please type a number \n >')
i2 = raw_input('please type a number \n >')
test(i1, i2) # here we call directly test() with entered "numbers"
如果您真的想在交互式提示符下进行测试,您可以这样做(如@FerdinandBeyer comment中所建议的):
然后,在提示下:
>>>var1, var2 = input()
please insert a number
> 3
please insert a number
> 2
>>>test(var1, var2)
最标准的方法是为测试方法提供参数:
def test(i1, i2):
try:
i1 = int(i1)
i2 = int(i2)
except ValueError:
print "you failed in typing a number"
def input():
i1 = raw_input('please type a number \n >')
i2 = raw_input('please type a number \n >')
test(i1, i2) # here we call directly test() with entered "numbers"
如果您真的想在交互式提示符下进行测试,您可以这样做(如@FerdinandBeyer comment中所建议的):
然后,在提示下:
>>>var1, var2 = input()
please insert a number
> 3
please insert a number
> 2
>>>test(var1, var2)
使用关键字“全局”
这导致i1和i2被视为全局变量(可在整个程序中访问),而不是局部变量(仅可在其定义的函数中访问-这导致了异常)使用关键字“全局”
这导致i1和i2被视为全局变量(可在整个程序中访问),而不是局部变量(仅可在定义它们的函数中访问-这导致了异常)这样考虑:常规变量,如
i1
和i2
是函数的局部变量,在函数外部不可见。您的函数input
创建test
未知的局部变量。如果要访问test
中的数据,则该数据必须是全局数据(请参阅全局变量的global
关键字)或使用函数参数明确指定给它(请参阅Cédrick Julien的答案)。根据经验,如果可能,应避免使用全局变量。请这样考虑:常规变量,如i1
和i2
是函数的局部变量,在函数外部不可见。您的函数input
创建test
未知的局部变量。如果要访问test
中的数据,则该数据必须是全局数据(请参阅全局变量的global
关键字)或使用函数参数明确指定给它(请参阅Cédrick Julien的答案)。根据经验,如果可能,应避免使用全局变量。+1input
应返回变量,以便OP可以在交互式提示中测试其功能:i1,i2=input();测试(i1,i2)
+1input
应返回变量,以便OP可以在交互式提示中测试其功能:i1,i2=input();测试(i1、i2)
。