Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Age Calculator from Birth Date

Calculate completed years from a full birth date with Python. Students compare month-day pairs to adjust for birthdays instead of subtracting birth years alone.

IntermediatePhase 6 - Category 5: Real-World Logic ProblemsExample 8 of 15
age-calculator-from-birth-date.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

Age: 24 years

This sample shows age 24 for a birth date of 15 May 2000. It assumes a current date from 15 May 2024 through 14 May 2025. date.today() uses the runtime local date, so a later run can show another completed age.

In this one

  • Construct a calendar date
  • Adjust for an upcoming birthday
  • Distinguish completed years from estimates

How it works

  1. 1

    Read birth year, month, and day into date.

  2. 2

    Subtract birth year from today's year.

  3. 3

    Subtract one more when this year's birthday is still ahead.

Walk through Age Calculator from Birth Date

Assume today is 10 May 2026 and birth date is 15 May 2000

  1. 1.The initial year difference is 26.
  2. 2.The tuple (5, 10) is before (5, 15).
  3. 3.Subtract one: completed age is 25 years.

Edge cases

Why compare month and day?

Why compare month and day?

The current year's birthday may still be ahead.

What happens for an impossible date?

What happens for an impossible date?

The date constructor raises ValueError.

What's going on

This version reads year, month, and day and counts completed birthdays. date constructs a real calendar date and today supplies the local current date.

The initial year difference is reduced by one when this year's birthday has not arrived. The saved output is a dated example, not a permanent age. Impossible dates raise ValueError; future birth dates are not separately rejected. February twenty-ninth follows the tuple comparison rule in nonleap years.

Why compare month and day? The current year's birthday may still be ahead.

What happens for an impossible date? The date constructor raises ValueError.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

How is this different from birth-year subtraction?

Pick an answer to check it.

Question 2

Why compare month and day?

Pick an answer to check it.

Questions people ask

Why compare month and day?

The current year's birthday may still be ahead.

What happens for an impossible date?

The date constructor raises ValueError.

How is this different from birth-year subtraction?

It adjusts for whether the birthday has occurred.