Calculate Age from Birth Year

Calculate current age from a given birth year using the current year.

PythonBeginner

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

  1. 1Import date from datetime.
  2. 2Read birth year from the user.
  3. 3Get the current year from the system.
  4. 4Subtract birth year from current year.
  5. 5Print the resulting age.