How do you go to the beginning of an if statement in the else section? Python 3.2

112 views Asked by At

The question is in the title: How do you go to the beginning of an if statement in the else section?

Code:

p1 = int(input())
if p1 <= 9 and p1 >= 1:
    pass
else:
    print('Invalid input. Please try again.')
    p1 = input()
1

There are 1 answers

0
Paul Rooney On BEST ANSWER

Run in a loop and never break out until the input meets the criteria.

while True:
    p1 = int(input("input something: "))
    if p1 <= 9 and p1 >= 1:
        break

    print('ERROR 404. Invalid input. Please try again.')

This code will throw an exception if you enter a value that cannot be converted to an int and terminate the program.

To get around this catch the exception and carry on.

while True:
    try:
        p1 = int(input("input something: "))

        if p1 <= 9 and p1 >= 1:
            break
    except ValueError:
        pass

    print('ERROR 404. Invalid input. Please try again.')