我刚开始编程并尝试写一些东西,但(当然)它失败了。在我遇到真正的问题之后: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
如何以Pythonic方式解决这个问题?或者我应该采取完全不同的方式?
答案 0 :(得分:6)
最常用的方法是为测试方法提供参数:
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评论中所述):
def test(i1, i2):
try:
i1 = int(i1)
i2 = int(i2)
except ValueError:
print "you failed in typing a number"
return i1, i2
def input():
i1 = raw_input('please type a number \n >')
i2 = raw_input('please type a number \n >')
return i1, i2
然后,提示:
>>>var1, var2 = input()
please insert a number
> 3
please insert a number
> 2
>>>test(var1, var2)
答案 1 :(得分:0)
使用关键字“global”。
def test():
global i1
global i2
try:
i1 = int(i1)
i2 = int(i2)
except ValueError:
print "you failed in typing a number"
def input():
global i1
global i2
i1 = raw_input('please type a number \n >')
i2 = raw_input('please type a number \n >')
这会导致i1和i2被视为全局变量(可在整个程序中访问)而不是局部变量(只能访问在中定义它们的函数 - 这会导致异常)