How to repeat try-except block

后端 未结 2 998
悲&欢浪女
悲&欢浪女 2021-01-01 21:18

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


        
2条回答
  •  星月不相逢
    2021-01-01 22:18

    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.

提交回复
热议问题