如何避免UnboundLocalError?

2024-04-23 21:02:00 发布

您现在位置: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('please type a number \n >')
    i2 = raw_input('please type a number \n >')

然后我写下:

^{pr2}$

然后我得到:

^{3}$

我怎样才能用Python的方式解决这个问题?或者我应该换一种方式吗?在


Tags: 代码testnumberinputrawdeftype编程
2条回答

使用“全局关键字”。在

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被视为全局变量(在整个程序中可访问),而不是局部变量(只能在中定义它们的函数中访问,这导致了异常)

最标准的方法是为测试方法提供参数:

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中建议的那样):

^{pr2}$

然后,一经提示:

>>>var1, var2 = input()
please insert a number
> 3
please insert a number
> 2 
>>>test(var1, var2)

相关问题 更多 >