Skip to content
Exercise · Exceptions · lesson 11 of 11

Exercise: parse an age

Write a function parse_age(text) that returns the age from the string text as an int. If int does not accept the string or the age lies outside the range from 0 to 150 inclusive, the function raises a ValueError.

  • parse_age("30") → 30
  • parse_age("abc") → ValueError
  • parse_age("151") → ValueError

Constraints: text is always a string; an integer is whatever int accepts, including "-1" and "12" but not "12.5"; the message in the ValueError may be anything.

Do not add extra imports unless the task says so explicitly.

parse_age.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way