What You'll Learn
- •Using datetime.date to get the current year
- •Performing simple date-based calculations
- •Adding basic validation checks
Python
# Program to calculate age from birth year
from datetime import date
birth_year = int(input("Enter your birth year: "))
current_year = date.today().year
if birth_year > current_year:
print("Birth year cannot be in the future.")
else:
age = current_year - birth_year
print("Your age is:", age)Output
Enter your birth year: 2000 Your age is: 25
We use datetime.date.today().year to get the current year dynamically.
Then:
- Validate that the birth year is not in the future.
- Subtract birth_year from current_year to get age.
This example introduces working with dates in Python.
Step-by-Step Breakdown
- 1Import date from datetime.
- 2Read birth year from the user.
- 3Get the current year from the system.
- 4Subtract birth year from current year.
- 5Print the resulting age.