anandh199g
anandh199g

Reputation: 121

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.

Upvotes: 2

Views: 4971

Answers (2)

wjandrea
wjandrea

Reputation: 32987

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.

Upvotes: 4

Geom
Geom

Reputation: 1546

You simply need to remove the finally: statement to achieve what you want.

while True:
    try:
        print('open')    
        num = int(input("Enter number:"))
        print(num)
        break # stop the loop when int() returns a value

    except ValueError:
        print('Error:"Please enter number only"') 
        continue

whatever you need to do after you validate the int() should be outside the try/except/finally structure

Upvotes: 1

Related Questions