Skip to content
C

Validated Age Input

Mediumpython

Write a program that repeatedly asks for an age until it receives a valid non-negative whole number, using try/except inside a loop.

What the problem means: keep reading a new line of input every time the previous one was invalid (not a number, or negative), and only stop once a good value arrives.

Approach: loop forever; inside the loop, try to convert the input to int and check it isn't negative — on failure (either a ValueError or a negative value), print the retry message and continue the loop; on success, print the accepted age and break.

Input: One or more lines: each is an attempted age (some may be invalid text or negative numbers); the last line is always a valid non-negative integer.

Output: Please enter a valid number once per invalid attempt, then finally Age accepted: <age>.

Input (stdin)

Output

Run your code to see output here...