How to repeat try-except block

余生颓废 提交于 2020-04-05 15:57:09

问题


I have a try-except block in Python 3.3, and I want it to run indefinitely.

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

Currently, if a user were to enter a non-integer it would work as planned, however if they were to enter it again, it would just raise ValueError again and crash.

What is the best way to fix this?


回答1:


Put it inside a while loop and break out when you've got the input you expect. It's probably best to keep all code dependant on imp in the try as below, or set a default value for it to prevent NameError's further down.

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

EDIT: user2678074 makes the valid point that this could make debugging difficult as it could get stuck in an infinite loop.

I would make two suggestions to resolve this - firstly use a for loop with a defined number of retries. Secondly, place the above in a function, so it's kept separate from the rest of your application logic and the error is isolated within the scope of that function:

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

With that in place, you can have a try/except outside of the function call and it'll only through if you go beyond the max number of retries.




回答2:


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

Output:

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:~$


来源:https://stackoverflow.com/questions/15232465/how-to-repeat-try-except-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!