我无法为这个确切的问题找到解决方案,以至于我希望有人可以对此有所了解。
我在这里有此代码:
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
但是当我第二次运行此函数并指定一个字符串时,将触发除外代码,并执行我的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
确保这真的很简单,我只需要对根本原因有一点了解。
答案 0 :(得分:0)
您可以执行以下操作-
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()
但是对于这个问题,递归是过大的。为什么?因为我们只会用函数调用填充内存堆栈,直到获得整数。因此while
循环就足够了-
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