gpt4 book ai didi

python - 如何解决 UnboundLocalError?

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:17 25 4
gpt4 key购买 nike

我刚开始编程并尝试写一些东西但(当然)它失败了。在我找到真正的问题之后: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 的方式解决这个问题?还是我应该采取完全不同的方式?

最佳答案

执行此操作的最标准方法是为您的测试方法提供参数:

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)

关于python - 如何解决 UnboundLocalError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8573254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com