Age Calculator

Calculate age from birth date.

IntermediatePhase 6 - Category 5: Real-World Logic ProblemsExample 8 of 15
age-calculator.py
1from datetime import date
2
3# Take birth date
4year = int(input("Enter birth year: "))
5month = int(input("Enter birth month: "))
6day = int(input("Enter birth day: "))
7
8# Calculate age
9today = date.today()
10birth_date = date(year, month, day)
11age = today.year - birth_date.year
12
13# Adjust if birthday hasn't occurred this year
14if (today.month, today.day) < (birth_date.month, birth_date.day):
15 age -= 1
16
17print(f"Age: {age} years")

Output

Enter birth year: 2000
Enter birth month: 5
Enter birth day: 15
Age: 24 years

What's going on

Calculate age from birth date.

Key Concepts:

Get current date
Calculate year difference
Adjust if birthday not passed