Calculate Age from Birth Year
Calculate current age from a given birth year using the current year.
BeginnerTopic: Basic Python Programs
What You'll Learn
- Using datetime.date to get the current year
- Performing simple date-based calculations
- Adding basic validation checks
Python Calculate Age from Birth Year Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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
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.
Understanding Calculate Age from Birth Year
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.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.