Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何重复试块_Python_Exception Handling_Python 3.x - Fatal编程技术网

Python 如何重复试块

Python 如何重复试块,python,exception-handling,python-3.x,Python,Exception Handling,Python 3.x,我在Python3.3中有一个try-except块,我希望它无限期地运行 try: imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low")) except ValueError: imp = int(input("Please enter a number between 1 and 3:\n> ") 目前,如果用户输入一个非整数,它将按计划工作,但是如果他们再次输入,它将再次引发ValueErr

我在Python3.3中有一个try-except块,我希望它无限期地运行

try:
    imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
except ValueError:
    imp = int(input("Please enter a number between 1 and 3:\n> ")
目前,如果用户输入一个非整数,它将按计划工作,但是如果他们再次输入,它将再次引发ValueError并崩溃


解决此问题的最佳方法是什么?

将其放入while循环中,并在获得预期输入时中断。最好保持所有代码依赖于
try
中的
imp
,如下所示,或者为其设置一个默认值,以防止
namererror

while True:
  try:
    imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))

    # ... Do stuff dependant on "imp"

    break # Only triggered if input is valid...
  except ValueError:
    print("Error: Invalid number")
编辑:user2678074指出,这可能会使调试变得困难,因为它可能陷入无限循环

我想提出两个建议来解决这个问题——首先使用一个具有一定重试次数的for循环。其次,将上述内容放在一个函数中,使其与应用程序逻辑的其余部分分开,并在该函数的范围内隔离错误:

def safeIntegerInput( num_retries = 3 ):
    for attempt_no in range(num_retries):
        try:
            return int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low"))
        except ValueError as error:
            if attempt_no < (num_retries - 1):
                print("Error: Invalid number")
            else:
                raise error
def safeIntegerInput(重试次数=3):
对于范围内的尝试次数(重试次数):
尝试:
返回int(输入(“重要性:\n\t1:High\n\t2:Normal\n\t3:Low”))
除ValueError作为错误外:
如果尝试次数<(重试次数-1):
打印(“错误:无效数字”)
其他:
提出错误

有了它,您可以在函数调用之外进行try/except,并且只有当您超过最大重试次数时,它才会通过。

我建议不要使用while循环,使用定义的重新尝试进行for循环。否则,会导致调试程序冻结非常困难。最好让程序在几次重试后以错误结束(在大多数情况下),因为回溯会告诉您它的工作不正确。
prompt = "Importance:\n\t1: High\n\t2: Normal\n\t3: Low\n> "
while True:
    try:
        imp = int(input(prompt))
        if imp < 1 or imp > 3:
            raise ValueError
        break
    except ValueError:
        prompt = "Please enter a number between 1 and 3:\n> "
rob@rivertam:~$ python3 test.py 
Importance:
    1: High
    2: Normal
    3: Low
> 67
Please enter a number between 1 and 3:
> test
Please enter a number between 1 and 3:
> 1
rob@rivertam:~$