PythonMastery

Input validation loop in Python

Keep asking the user until they type a valid whole number in a range. Uses a while loop, try/except ValueError and a range check in one reusable function.

Users type unexpected things: words, decimals, empty lines, numbers that are too big. This program keeps asking until the answer is a whole number from 1 to 10, and it explains each mistake.

The program

python
def ask_whole_number(prompt, low, high):
    while True:
        text = input(prompt).strip()
        if text == "":
            print("Please type something.")
            continue
        try:
            number = int(text)
        except ValueError:
            print(f"{text!r} is not a whole number.")
            continue
        if low <= number <= high:
            return number
        print(f"Please choose a number from {low} to {high}.")


rating = ask_whole_number("Rate the film from 1 to 10: ", 1, 10)
print(f"Thank you. You gave it {rating} out of 10.")

Typed in this example: (just Enter), seven, 7.5, 15, -3, 8. Press Run to type your own.

output
Rate the film from 1 to 10: 
Please type something.
Rate the film from 1 to 10: seven
'seven' is not a whole number.
Rate the film from 1 to 10: 7.5
'7.5' is not a whole number.
Rate the film from 1 to 10: 15
Please choose a number from 1 to 10.
Rate the film from 1 to 10: -3
Please choose a number from 1 to 10.
Rate the film from 1 to 10: 8
Thank you. You gave it 8 out of 10.

How it works

Because the checks are inside a function, you can use them for any question, for example age = ask_whole_number("Age: ", 0, 120).

The program does not trust the input at any point. This is the habit to keep for all user input, and also for data from files and websites. The number guessing game uses the same pattern inside a game loop.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Errors & Exceptions: When Things Go Wrong