Practice: Validate Age

Practice: Validate Age

This exercise combines try/except and raise in one function — the shape of most input validation: convert, check, and raise with a clear message when the input is unusable.

Exercise

  1. Define a function named validate_age with one parameter, text.
  2. Convert text to an int. If the conversion fails, raise ValueError with the message age must be a whole number.
  3. If the number is below 0 or above 120, raise ValueError with the message age out of range.
  4. Otherwise return the number.

validate_age("42") returns 42. validate_age("abc") and validate_age("130") both raise ValueError.

Run your code to see the output, then press Submit.

Hints

  • Catch the ValueError from int(text) and raise your own with the required message.
  • Do the range check after the conversion, outside the try.

Tests

import unittest


class TestValidateAge(unittest.TestCase):
    def test_valid_age(self):
        self.assertEqual(validate_age("42"), 42)

    def test_zero_is_valid(self):
        self.assertEqual(validate_age("0"), 0)

    def test_letters_raise_with_message(self):
        with self.assertRaises(ValueError) as context:
            validate_age("abc")
        self.assertEqual(str(context.exception), "age must be a whole number")

    def test_negative_age_raises_with_message(self):
        with self.assertRaises(ValueError) as context:
            validate_age("-1")
        self.assertEqual(str(context.exception), "age out of range")

    def test_130_raises_with_message(self):
        with self.assertRaises(ValueError) as context:
            validate_age("130")
        self.assertEqual(str(context.exception), "age out of range")
def validate_age(text):
    try:
        age = int(text)
    except ValueError:
        raise ValueError("age must be a whole number")
    if age < 0 or age > 120:
        raise ValueError("age out of range")
    return age


print(validate_age("42"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.