Python conversion and input validation

Text from a form or terminal is not automatically an integer. int converts valid integer text and raises ValueError for invalid numeric syntax.

Python
def parse_age(text):
    try:
        age = int(text)
    except ValueError:
        return "Invalid integer"
    if age < 0:
        return "Age cannot be negative"
    return str(age)

print(parse_age("21"))
print(parse_age("abc"))
print(parse_age("-1"))
assert parse_age("0") == "0"
Read the full lesson