Skip to content

Commit b42910d

Browse files
authored
Add age_controller.py with validate_age function (issue TheAlgorithms#12809)
This module validates and processes age input, ensuring it is a positive integer within the range of 0 to 150. It includes error handling for invalid inputs and provides examples in the docstring.
1 parent c79034c commit b42910d

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

age_controller.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""Age Controller Module
2+
3+
This module provides functionality to validate and process age input.
4+
Related to issue #12809.
5+
"""
6+
7+
8+
def validate_age(age):
9+
"""Validate and process age input.
10+
11+
This function validates that the provided age is a valid positive integer
12+
within a reasonable range (0-150 years).
13+
14+
Args:
15+
age: The age input to validate (can be int, str, or float)
16+
17+
Returns:
18+
int: The validated age as an integer
19+
20+
Raises:
21+
ValueError: If age is invalid, negative, or out of range
22+
TypeError: If age cannot be converted to a number
23+
24+
Examples:
25+
>>> validate_age(25)
26+
25
27+
>>> validate_age('30')
28+
30
29+
>>> validate_age(45.0)
30+
45
31+
>>> validate_age(-5)
32+
Traceback (most recent call last):
33+
...
34+
ValueError: Age must be a positive number
35+
>>> validate_age(200)
36+
Traceback (most recent call last):
37+
...
38+
ValueError: Age must be between 0 and 150
39+
>>> validate_age('invalid')
40+
Traceback (most recent call last):
41+
...
42+
ValueError: Age must be a valid number
43+
"""
44+
try:
45+
# Convert to float first to handle string numbers
46+
age_float = float(age)
47+
48+
# Check if it's a whole number
49+
if age_float != int(age_float):
50+
age_int = int(age_float)
51+
else:
52+
age_int = int(age_float)
53+
54+
except (ValueError, TypeError):
55+
raise ValueError("Age must be a valid number")
56+
57+
# Validate range
58+
if age_int < 0:
59+
raise ValueError("Age must be a positive number")
60+
61+
if age_int > 150:
62+
raise ValueError("Age must be between 0 and 150")
63+
64+
return age_int
65+
66+
67+
if __name__ == "__main__":
68+
import doctest
69+
doctest.testmod()

0 commit comments

Comments
 (0)