关于python:如何重复try-except块

How to repeat try-except block

我在Python 3.3中有一个try-except块,并且希望它无限期运行。

1
2
3
4
5
6
7
8
try:
    imp = int(input("Importance:
\t1: High
\t2: Normal
\t3: Low"
))
except ValueError:
    imp = int(input("Please enter a number between 1 and 3:
>"
)

当前,如果用户输入一个非整数,它将按计划工作,但是,如果他们再次输入,它将再次引发ValueError并崩溃。

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


将其放入while循环中,并在获得所需输入时中断。 最好使所有代码依赖于try中的imp,如下所示,或者为其设置默认值以防止NameError进一步下降。

1
2
3
4
5
6
7
8
9
10
11
12
while True:
  try:
    imp = int(input("Importance:
\t1: High
\t2: Normal
\t3: Low"
))

    # ... Do stuff dependant on"imp"

    break # Only triggered if input is valid...
  except ValueError:
    print("Error: Invalid number")

编辑:user2678074提出了有效点,这可能会使调试变得困难,因为它可能陷入无限循环。

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

1
2
3
4
5
6
7
8
9
10
11
12
def safeIntegerInput( num_retries = 3 ):
    for attempt_no in range(num_retries):
        try:
            return int(input("Importance:
\t1: High
\t2: Normal
\t3: Low"
))
        except ValueError as error:
            if attempt_no < (num_retries - 1):
                print("Error: Invalid number")
            else:
                raise error

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
prompt ="Importance:
\t1: High
\t2: Normal
\t3: Low
>"

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:
>"

输出:

1
2
3
4
5
6
7
8
9
10
11
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:~$