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
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.
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
while Truerepeats until areturnends the function.returnonly runs when the number passes both checks.int(text)raises aValueErrorforsevenand for7.5, becauseint()only accepts text that looks like a whole number.low <= number <= highis a chained comparison. It meanslow <= number and number <= high..strip()removes spaces around the answer. Without it, an answer of only spaces would pass the empty check and then fail inint()with a less helpful message.{text!r}shows the text with quotes, so the user can see exactly what they typed.
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.