Skip to Content
Python while Loops: Keep Asking Until the Input Is Valid
Beginner
0 likes
Tutorials

Python while Loops: Keep Asking Until the Input Is Valid

People type the wrong thing, sometimes more than once. A while True loop with try/except, a range check and a way out keeps asking until the answer is usable, so the rest of your code never has to check again.

If your program asks a person for a number, assume they'll type something else at least once. Not because people are careless. Because they press Enter by accident, type "twenty", or add a space. A while loop that keeps asking until the answer is valid is the standard fix, and it's only a few lines.

Skip ahead: If you only want the pattern, copy the code in "The pattern" and adjust the check. Read "Giving people a way out" before you use it for real.

Why if is not enough

The first try usually looks like this:

age = input("Your age: ")
if not age.isdigit():
    age = input("Please type a number: ")
age = int(age)

It checks once. If the person types something wrong twice, int() crashes on the second bad answer. You could add another if, and another. You'd never have enough. You don't know how many times someone will get it wrong, and that's exactly the job of a while loop: repeat until a condition changes, however many times that takes.

The pattern

while True:
    text = input("Your age: ").strip()
    try:
        age = int(text)
    except ValueError:
        print("Please type a whole number, like 25.")
        continue
    if age < 0 or age > 130:
        print("That age doesn't look right. Try again.")
        continue
    break

print(f"Thanks. You are {age}.")

Here's what a session looks like when someone types twenty, presses Enter on an empty line, types -4, then 25:

Your age: twenty
Please type a whole number, like 25.
Your age: 
Please type a whole number, like 25.
Your age: -4
That age doesn't look right. Try again.
Your age: 25
Thanks. You are 25.

How it works:

  1. **while True:** loops forever, on purpose. The loop only ends at break.
  2. **.strip()** removes spaces around the answer, so " 25 " works.
  3. **try/except ValueError** catches anything int() can't read: words, decimals, an empty answer.
  4. **continue** jumps back to the top and asks again.
  5. The range check comes after the conversion. "Is it a number?" and "Is it a sensible number?" are two separate questions.
  6. **break** is only reached when every check passed. After the loop, age is guaranteed to be valid.

That last point is the whole reason for the pattern. Code after the loop never has to check again.

💡 Tip: Tell the person what a good answer looks like. "Invalid input" helps nobody. "Please type a whole number, like 25" tells them what to do.

Why not isdigit()?

You'll see text.isdigit() used for this. It works for simple cases, but it says no to -4 (so you can't give a useful "that's negative" message), and it says yes to some characters int() can't read, like "²". Trying the conversion and catching the error is more honest: you're asking the exact function you'll use whether it can read the text.

for text in ["25", "-4", "²", " 25"]:
    print(repr(text), text.isdigit())
'25' True
'-4' False
'²' True
' 25' False

Turn it into a function

Once you have more than one question, put the pattern in a function:

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


quantity = ask_int("How many? ", 1, 50)
table = ask_int("Table number? ", 1, 12)
print(f"{quantity} items for table {table}")
How many? 0
Please choose a number from 1 to 50.
How many? 3
Table number? 15
Please choose a number from 1 to 12.
Table number? 7
3 items for table 7

return inside the loop ends both the loop and the function. You don't need break here.

Giving people a way out

A loop that can only end with a valid answer can trap someone who wants to quit. For anything beyond a small exercise, accept a word that means "stop":

while True:
    text = input("Amount (or q to quit): ").strip().lower()
    if text == "q":
        print("Cancelled.")
        break
    try:
        amount = float(text)
    except ValueError:
        print("Please type a number, or q to quit.")
        continue
    print(f"Saved {amount:.2f}")
    break
Amount (or q to quit): abc
Please type a number, or q to quit.
Amount (or q to quit): q
Cancelled.

âš  Warning: If you test a loop that never ends, stop it with Ctrl+C in the terminal. That's normal, not a crash of your computer. But check why it didn't end: usually the break is never reached, or the variable in the while condition never changes.

Common mistakes

  • **Converting before the try.** int(input()) outside a try crashes on the first bad answer. The conversion must be inside.
  • **Forgetting continue after the error message.** The code keeps going with no valid age, and fails somewhere else.
  • Checking the range before converting. You can't compare "twenty" with 130.
  • No way out. Fine for a beginner exercise, annoying in a real tool.

What happens if you skip validation

The program works every time you test it, because you know what to type. The first person who doesn't gets a traceback instead of a question. Or worse, a wrong value gets saved and used later, far from where it came in.

If your program asks for a quantity and someone types 2.5, what should happen: reject it, round it, or accept it? And does your loop do that?

About

The keep-asking pattern with while True, try/except, continue and break, turned into a reusable function with a way to quit. After this, a wrong answer gets a helpful message instead of a crash.

Responsible
Jay P
Last Update
09/24/2026
Reading Time
5 min
Was this helpful?
​ 0 ​ 0

Comments (0)

Sign in to comment

No comments yet.