samedi 30 mars 2019

Problem with try and if statement in a while loop

I thought I clearly understand the exception handling, while loop and conditional statements. But I came across this simple problem that my code execution never reaches the except statement.

I made the code as simple as possible to point out the problem. So the code requires to press '1'. Only then it can escape the while loop. Anything else should go to exception. Characters, such as 'a' and 'b' does - because they cannot be converted to an integer. But any other number does not trigger the exception. It just goes back to the input step. Why is it like that? Clearly any other number except 1 is not equal to 1.

while True:
    click = input('Press 1')
    try:
        if int(click) == 1:
            print('correct')
            break
    except:
        print('wrong')

Aucun commentaire:

Enregistrer un commentaire