Here's a challenging Python project: The Age Calculator. It asks the user for their birthdate, calculates how long ago that was, and outputs the result in text.
So how do you build an age calculator in Python? Let's go over the full source code, step by step.
Python Age Calculator: The Full Code
Here's the full code for this Python project.
I'll break it down into parts and explain each, though I've included notes to show why each segment is used throughout.
from datetime import date
def calculate_age(birthdate):
today = date.today()
# Calculate age in years
age_years = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
# Calculate age in months and days
if today.month < birthdate.month or (today.month == birthdate.month and today.day < birthdate.day):
age_months = (12 - birthdate.month) + today.month - 1
else:
age_months = today.month - birthdate.month
# Calculate days
if today.day < birthdate.day:
# Go back one month to get the correct number of days
# in the previous month
month_ago = (today.month - 1) if today.month > 1 else 12
days_in_month = (date(today.year, today.month, 1) - date(today.year, month_ago, 1)).days
age_days = days_in_month - (birthdate.day - today.day)
else:
age_days = today.day - birthdate.day
return age_years, age_months, age_days
def main():
# Input birthdate from the user
birthdate_str = input("Enter your birthdate (YYYY-MM-DD): ")
year, month, day = map(int, birthdate_str.split('-'))
birthdate = date(year, month, day)
# Calculate age
age_years, age_months, age_days = calculate_age(birthdate)
# Output the age
print(f"You are {age_years} years, {age_months} months, and {age_days} days old.")
if __name__ == "__main__":
main()
You an import my full source code into your Python IDE and run it yourself. Of course, you're also welcome to use it as the foundation of your own projects.
Importing Libraries
You only need to import one class from one module for this function.
from datetime import date
From the datetime library, you're importing "date".
So what is datetime date?
When we say "from datetime import date", what we mean is that we're only importing the date class from the datetime module.
The datetime module, as explained in the Python official docs, allows you to work with year, month, and day.
If we wanted to build the simplest version of this age calculator, it might start with something like this:
from datetime import date
def calculate_age(birthdate):
today = date.today()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
return age
# Example usage
birthdate = date(1982, 7, 10) # Year, Month, Day
age = calculate_age(birthdate)
print(f"Age: {age}")
Calculating Age in Python
Once you've imported the date class from datetime, you can use it immediately. In fact, you need it if you want to use the today() method.
from datetime import date
# Get today's date
today = date.today()
print(f"Today's date is: {today}")
This Python code shows how you call today's date, which you'll need to do if you want your calculator to find someone's current age.
Note that we use today() to define the variable, "today".
today = date.today()
Once that variable is defined, we can use it to calculate age by subtracting a birthdate from today's date.
We do that here:
# Calculate age in months and days
if today.month < birthdate.month or (today.month == birthdate.month and today.day < birthdate.day):
age_months = (12 - birthdate.month) + today.month - 1
else:
age_months = today.month - birthdate.month
# Calculate days
if today.day < birthdate.day:
# Go back one month to get the correct number of days
# in the previous month
month_ago = (today.month - 1) if today.month > 1 else 12
days_in_month = (date(today.year, today.month, 1) - date(today.year, month_ago, 1)).days
age_days = days_in_month - (birthdate.day - today.day)
else:
age_days = today.day - birthdate.day
return age_years, age_months, age_days
Creating the User Interface
We already built a Python age calculator. But we still need a way for people to interact with it.
So let's define our main() function.
We need the function to ask for the user's birthdate. We use that variable in our calculation. Then, we need to perform the calculation.
So let's have it do exactly that.
# Input birthdate from the user
birthdate_str = input("Enter your birthdate (YYYY-MM-DD): ")
year, month, day = map(int, birthdate_str.split('-'))
birthdate = date(year, month, day)
# Calculate age
age_years, age_months, age_days = calculate_age(birthdate)
# Output the age
print(f"You are {age_years} years, {age_months} months, and {age_days} days old.")
Nest this inside a def main(): and we've done it.
The result? An age calculator!
Looking for another challenge? Here's my guide on building a hangman game in Python.
Why Build an Age Calculator in Python?
There are many reasons you may want to tackle this Python project, but the long term goal is the same. We learn these skills because they're powerful tools. And it's helpful to understand Python for myriad job opportunities.
Once you're familiar with the coding language, you can get certified as an expert. We've written about Python certifications in the past. These distinctions are popular for a few reasons. The first? Python is one of the top three programming languages in the world (according to a recent StackOverflow survey). And Python jobs pay well.
So an age calculator might be a simple project, but it's a foundation. It helps you build a knowledge base for bigger projects. . . including data analytics and artificial intelligence projects.