Validate and Convert Age Input

Medium ⏱ 12 min 50% acceptance ★★★★★ 4.7
Write a function parse_age(raw) that safely converts a user-entered string raw into a valid age. Return the integer age if raw represents a whole number between 0 and 120 inclusive. Otherwise, return the string "invalid age". Handle non-numeric strings, negative numbers, decimals, and out-of-range values.

Examples

Example 1
Input
parse_age("29")
Output
29
Explanation

Valid integer within range.

Example 2
Input
parse_age("-5")
Output
'invalid age'
Explanation

Negative ages are not allowed.

Example 3
Input
parse_age("abc")
Output
'invalid age'
Explanation

Not a number at all.

Example 4
Input
parse_age("30.5")
Output
'invalid age'
Explanation

Not a whole number.

Constraints

  • raw is always a string.
  • Valid range is 0 to 120 inclusive, whole numbers only.

Topics

Input & Outputinput validation

Companies

TCSHCLTechWipro

Hints

Hint 1

Use try/except around int(raw) to catch non-numeric strings (int() rejects "30.5").

Hint 2

After parsing, check the 0-120 bound explicitly.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.