Course outline · 0% complete

0/32 lessons0%

Course overview →

Retry Until Valid

lesson 9-3 · ~10 min · 29/32

The ask-again loop

Crashing on the first bad keystroke is not acceptable in real software, and silently accepting garbage is worse. The standard fix combines three tools you already own: while True: from lesson 5-2, try/except from lesson 9-2, and break. Attempt the conversion, and only break out of the loop once it succeeds:

while True:
    raw = input()
    try:
        n = int(raw)
        break
    except ValueError:
        print("not a number, try again")

The break sits inside the try, on the line after the conversion, because that placement encodes the logic: reaching the break proves int(raw) did not raise, so the loop only ends on success. Every command-line tool that asks for a number, a date, or a menu choice runs a loop of exactly this shape.

Code exercise · python

Run it. The stdin plays a stubborn user: `abc`, then `4.5` (which int() also rejects, it only accepts whole-number text), then `12`. Two rejections, then success.

Quiz

In the ask-again loop, why does the break sit on the line AFTER `n = int(raw)`, inside the try?

Code exercise · python

Your turn, with two kinds of bad input. Read an age until it is valid: on ValueError print `digits only please`, on a negative number print `age cannot be negative` and keep asking. When a valid age arrives, leave the loop and print like `age recorded: 20`. Stdin plays: `twenty`, `-3`, `20`.

Problem

A user runs the basic ask-again loop from this lesson and types `ten`, then `10`. How many times does the except block execute?