Validating Python input() with a while Loop

Re-ask until the answer is actually valid — using a while loop wrapped around input().

  • Lesson 5 of 5
  • PRO
  • Ages 10+
  • 3 hands-on levels
See what PRO unlocksA one-time $49.99 purchase. Topics 1–3 are free.

The dragon explains

Validating input

  1. The dragon: So far, every level trusted the player's FIRST answer. Real programs can't always do that.

  2. The dragon: You already know while loops repeat until a condition changes. Wrap one around input(), and you can keep asking until the answer is actually good.

    example.pyPython 3
    while True:    answer = input("Password? ")    if answer == "dragon":        break    print("Nope, try again.")print("The gate opens!")
    OutputNope, try again. The gate opens!
  3. The dragon: while True: means 'repeat forever' — the ONLY way out is the break inside the if. That's the whole pattern: ask, check, break if good, otherwise loop back and ask again.

    example.pyPython 3
    while True:    answer = input("Password? ")    if answer == "dragon":        break    print("Nope, try again.")
  4. The dragon: This works for numbers too — not just wrong answers, but numbers that convert fine but break a GAME rule, like gold that shouldn't be negative.

  5. The dragon: int('-5') converts perfectly well — it's a real, valid number. The while loop re-asks because -5 fails YOUR rule (gold > 0), not because Python refused to convert it.

    example.pyPython 3
    while True:    gold = int(input("Gold? "))    if gold > 0:        break    print("Try again.")
  6. The dragon: But some text can't be converted AT ALL — and that's a different, real crash.

  7. The dragon: int('abc') raises a ValueError. Not the TypeError from before — this is Python saying 'abc' was never digits, so there's nothing to convert.

    example.pyPython 3
    int('abc')
    OutputValueError: invalid literal for int() with base 10: 'abc'
  8. The dragon: answer.isdigit() checks whether text is made ENTIRELY of digits, without converting it — True or False, and it never crashes, even on 'abc'.

    example.pyPython 3
    print("abc".isdigit())
    OutputFalse
  9. The dragon: Put it together: check .isdigit() BEFORE calling int(), inside a while loop. Bad text gets re-asked instead of ever reaching int() at all.

    example.pyPython 3
    while True:    age_text = input("Age? ")    if age_text.isdigit():        age = int(age_text)        break    print("Not a whole number — try again.")

Quick check

Check your understanding

Say your answer out loud before reading the marked one. Every wrong option is a mistake real beginners make.

  1. Question 1 of 3

    A level re-asks "Password? " until the player types "dragon", using while True: with a break inside an if. The player types "wrong" first, then "dragon". How many times does the loop ask?

    question.pyPython 3
    while True:    answer = input("Password? ")    if answer == "dragon":        break    print("Nope, try again.")
    • Twice — once for the wrong guess, once for the right oneCorrect
    • Once — checking the answer once is enough to know if it's valid
    • Forever — while True: never stops

    Why: Twice. The first answer (wrong) fails the if, so the loop asks again; the second answer (dragon) passes the if and break ends the loop. while True: plus a break is exactly how you repeat 'ask again' an unknown number of times, however many wrong guesses it takes.

  2. Question 2 of 3

    gold = int(input("Gold? ")) and the player types "-5". Does this crash?

    question.pyPython 3
    gold = int(input("Gold? "))
    • No — int('-5') converts fine, it's a real (negative) numberCorrect
    • Yes — int() can't handle negative numbers

    Why: No crash — int('-5') is a completely valid conversion. Rejecting -5 as bad gold is a rule YOUR code has to check with an if, same as any other re-ask loop, not something int() does automatically.

  3. Question 3 of 3

    The player types "abc" where the code does int(input("Age? ")). What happens?

    question.pyPython 3
    age = int(input("Age? "))
    • A ValueError — 'abc' isn't digits, so there's nothing to convertCorrect
    • A TypeError, same as forgetting int() entirely
    • Nothing — int() just returns 0 for text it can't convert

    Why: A ValueError — Python's honest way of saying 'abc' was never digits, so int() has nothing valid to convert. Checking answer.isdigit() BEFORE calling int() is how you avoid ever triggering it.

In the game

What you'll practice

Three levels in the game: one guided first try with the shape of the answer already there, then two to solve on your own.

  1. 1

    GuidedYour first try

    The dragon's gate only opens for the password "dragon". Keep asking "Password? " until the answer is exactly "dragon" — print "Nope, try again." for every wrong guess, then once the right password arrives, break out and print "The gate opens!". The player will answer wrong once, then right.

  2. +2

    PracticeTwo more, on your own

This lesson is part of PRO.

PRO is a one-time $49.99 purchase, no subscription, and unlocks this whole topic along with everything else. Topics 1–3 are free, start to finish.

Unlock this lesson with PRO

Stuck three times? The game offers the answer — unasked.