Python Input Loops: Keep Asking Until It's Right
Keep Asking Until the Answer Is Valid
An input loop is a while loop that calls input() again and again. Its first job: keep asking until the user gives a valid answer, instead of stopping at the first mistake.
In chapter 8, an if could only complain about bad input once. A while can ask again:
marks = int(input())
while marks < 0 or marks > 100:
print("Marks must be 0 to 100. Try again.")
marks = int(input())
print("Saved:", marks)Marks must be 0 to 100. Try again. Marks must be 0 to 100. Try again. Saved: 80
The Input box has three lines, one for each input() call: 150 and -5 fail the check, and 80 passes. Change the lines and run it again.
Think of a shop assistant who asks your shoe size. Say "99", and they ask again, until you say a size they have.
The pattern
- Ask once before the loop.
- While the answer is bad: say what's wrong, and ask again inside the loop.
- After the loop, the answer is sure to be good.
The input() inside the loop is the loop's change: it's the line that can make the condition False. Leave it out, and you get an endless loop, printing "Try again" forever.
Write the bad case in the condition
The condition describes a bad answer, because that's when the loop should keep going:
| You want | The while condition |
|---|---|
| a number from 1 to 10 | while n < 1 or n > 10: |
| more than 0 | while n <= 0: |
| the right PIN | while pin != "1234": |
Common beginner doubt: "What if the user types abc?" Then int() stops the program with a ValueError, before the loop can help. Catching that needs try and except, from chapter 17.
Ask once, then while the answer is bad, explain and ask again.