pythonpython-3.xpython-3.2

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


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()

Solution

  • 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.')