Python Input Validation: Ask Again with try except
Ask Again Until the User Types a Number
Input validation means checking what the user typed before you use it. With while True, try and except together, your program can keep asking until it gets a real number, instead of crashing at the first typo.
while True:
try:
number = int(input())
break
except ValueError:
print("Please type a whole number.")
print("You typed", number)Please type a whole number. Please type a whole number. You typed 7
The Input box has three lines. abc and 2.5 fail, and the program asks again. 7 works, and the loop ends.
This is the promise from chapters 7 and 11: no more crashes when the user types a word instead of a number.
Think of it like a ticket machine that gives your coin back when it doesn't fit, and waits for another one. It never breaks down. It just asks again.
How it works
while True:repeats forever, until abreak(chapter 11).- Inside the
try,int()tries to convert the input. - If it works, the next line,
break, ends the loop. - If it fails, Python jumps to
except, skipping thebreak. The message prints, and the loop asks again. - After the loop,
numberis sure to be a whole number.
The same loop with else
You can also put the break in an else block. It runs only when int() worked:
while True:
try:
number = int(input())
except ValueError:
print("Please type a whole number.")
else:
break
Both versions work the same way. The else version keeps the try block to the one risky line.
Common beginner doubt: "Isn't while True an endless loop?" Only if nothing ever reaches the break. Here the break runs as soon as the user types a valid number, so the loop always has a way out.
while True, try int(input()), break on success, and print a message in except.