Search code examples
pythonpython-3.xwhile-looptry-exceptcontinue

While loop "continue" not working inside try, except, finally


Trying to run a while loop until the input is valid:

while True:
    try:
        print('open')    
        num = int(input("Enter number:"))
        print(num)

    except ValueError:
        print('Error:"Please enter number only"') 
        continue #this continue is not working, the loop runs and break at finally

    finally:
        print('close')
        break

Need to continue the loop if anything except numbers is entered, but the loop reaches finally and breaks.


Solution

  • finally will always run after the try-except. You want else, which will run only if the try-block doesn't raise an exception.

    By the way, minimize the code in a try-block, to avoid false-positives.

    while True:
        inp = input("Enter number: ")
        try:
            num = int(inp)
        except ValueError:
            print('Error: Please enter number only')
            continue
        else:
            print(num)
            break
        print('This will never print')  # Added just for demo
    

    Test run:

    Enter number: f
    Error: Please enter number only
    Enter number: 15
    15
    

    Note that the continue is not actually needed in your example, so I added a demo print() at the bottom of the loop.