Python builtins.UnboundLocalError:局部变量

Python builtins.UnboundLocalError:局部变量,python,python-3.x,Python,Python 3.x,我还没能找到一个解决这个问题的方法,所以我希望有人能对此有所帮助 我这里有这个代码: def numberOfPorts(): try: ports = int(input("How many ports do you want to configure? ")) except: print("You did not specify a number.") numberOfPorts() return ports 现在,如

我还没能找到一个解决这个问题的方法,所以我希望有人能对此有所帮助

我这里有这个代码:

def numberOfPorts():
    try:
        ports = int(input("How many ports do you want to configure? "))
    except:
        print("You did not specify a number.")
        numberOfPorts()
    return ports
现在,如果我运行这段代码并输入一个数字,该函数运行良好

numberOfPorts()
How many ports do you want to configure? 10
10
但是当我第二次运行这个函数并指定一个字符串时,会触发except代码,执行print语句,输入函数再次请求输入。这就是我想要的。然后,我给脚本一个数字,但得到以下错误:

numberOfPorts()
How many ports do you want to configure? foobar
You did not specify a number.
How many ports do you want to configure? 10
Traceback (most recent call last):
  Python Shell, prompt 53, line 1
  Python Shell, prompt 49, line 8
builtins.UnboundLocalError: local variable 'ports' referenced before assignment

我相信这真的很简单,我只需要了解一下根本原因

你可以这样做-

def numberOfPorts():
    try:
        ports = int(input("How many ports do you want to configure? "))
        return ports
    except:
        print("You did not specify a number.")
        return numberOfPorts()
但是递归对于这个问题来说是一种过度的杀伤力。为什么?因为我们将用函数调用填充内存堆栈,直到得到一个整数。所以
循环就足够了-

def numberOfPorts():
    ports = None
    while ports is None:
        try:
            ports = int(raw_input("How many ports do you want to configure? "))
        except ValueError:
            print("You did not specify a number.")
    return ports

在异常情况下,
try
从未完成,因此从不设置
端口。然后,当您确实获得了一个有效值时,它就存在于递归函数调用的上下文中,这是一个不同的作用域。使用
循环时,不要对此使用递归。@avigil好的,这是有意义的。因此,正如“abccd”所提到的,建议在这种上下文中使用while循环吗?@JoelDeLaTorre在Python中,您几乎总是希望使用一些循环控制结构而不是递归。有一些算法更自然地以递归形式表示,在这种情况下,继续,但在这里使用while循环。我会在这里使用
None
而不是
0
,因为
0
可能是合理的用户输入。还有一件事,当端口为None时使用
None
在python中是
falsy
,因此
not None
truthy
是,但是它将接受任何falsy值,包括
0
,这是我们试图避免的。除了
块中的
pass
是不必要的