Age Calculator in Python
About the project:Age Calculator project in Python will be a standalone script that calculates a person's age based on their birth date and the current date.
This Python script uses the built-in datetime module to handle date calculations.
It will promptHow to use this Age Calculator:
- Run the Python script.
- When you run this script, and it will continue to prompt you to enter your birth date in the YYYY-MM-DD format and will then tell you your exact age in years, months, and days.
When you run the script, it will perform a single calculation before exiting. If you want to perform another calculation, you'll need to run the script again.
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# age_calculator.py
from datetime import date
import sys
def get_valid_date_input(prompt):
"""
Helper function to get a valid date from the user.
It prompts for year, month, and day and ensures they are valid.
"""
while True:
try:
date_str = input(prompt).strip()
# Check for a "q" to quit the program gracefully
if date_str.lower() == 'q':
return None
parts = list(map(int, date_str.split('-')))
if len(parts) != 3:
print("Invalid date format. Please use YYYY-MM-DD.")
continue
year, month, day = parts
# Use date constructor to validate the date
return date(year, month, day)
except ValueError:
print("Invalid date. Please use the format YYYY-MM-DD and ensure the date is valid.")
def calculate_age(birth_date):
"""
Calculates the age in years, months, and days.
Returns a tuple of (years, months, days).
"""
today = date.today()
# Calculate years
years = today.year - birth_date.year
# Calculate months and adjust years if birthday hasn't occurred yet
months = today.month - birth_date.month
if months < 0:
years -= 1
months += 12
# Calculate days and adjust months if day has not occurred yet
days = today.day - birth_date.day
if days < 0:
months -= 1
# The number of days in the preceding month
if today.month == 1:
# Special case for January
days += date(today.year - 1, 12, 31).day
else:
days += date(today.year, today.month - 1, 1).day
return years, months, days
def main():
"""Main function to run the Age Calculator."""
print("--- Python Age Calculator ---")
print("Enter your birth date in YYYY-MM-DD format (or 'q' to quit).")
birth_date = get_valid_date_input("Enter your birth date: ")
if birth_date is None:
return
years, months, days = calculate_age(birth_date)
print(f"\nYou are {years} years, {months} months, and {days} days old.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
Below is another code snippet with additional Project functions to make it even more useful.
This is the updated "Python Age Calculator" included a continuous loop and a feature to calculate the number of days until your next birthday.
The main function now runs in a continuous loop, allowing you to calculate multiple ages without restarting the script.
I also added a new function days_until_next_birthday to calculate the number of days remaining until your next birthday, which is then displayed along with your age.
# age_calculator.py
from datetime import date
import sys
def get_valid_date_input(prompt):
"""
Helper function to get a valid date from the user.
It prompts for year, month, and day and ensures they are valid.
"""
while True:
try:
date_str = input(prompt).strip()
# Check for a "q" to quit the program gracefully
if date_str.lower() == 'q':
return None
parts = list(map(int, date_str.split('-')))
if len(parts) != 3:
print("Invalid date format. Please use YYYY-MM-DD.")
continue
year, month, day = parts
# Use date constructor to validate the date
return date(year, month, day)
except ValueError:
print("Invalid date. Please use the format YYYY-MM-DD and ensure the date is valid.")
def calculate_age(birth_date):
"""
Calculates the age in years, months, and days.
Returns a tuple of (years, months, days).
"""
today = date.today()
# Calculate years
years = today.year - birth_date.year
# Calculate months and adjust years if birthday hasn't occurred yet
months = today.month - birth_date.month
if months < 0:
years -= 1
months += 12
# Calculate days and adjust months if day has not occurred yet
days = today.day - birth_date.day
if days < 0:
months -= 1
# The number of days in the preceding month
if today.month == 1:
# Special case for January
days += date(today.year - 1, 12, 31).day
else:
days += date(today.year, today.month - 1, 1).day
# Correct for negative month and day values after adjustments
if months < 0:
years -= 1
months += 12
if days < 0:
months -= 1
days += (date(today.year, today.month, 1) - date(today.year, today.month-1, 1)).days
return years, months, days
def days_until_next_birthday(birth_date):
"""
Calculates the number of days until the next birthday.
Returns the number of days as an integer.
"""
today = date.today()
# Get the date of this year's birthday
this_year_birthday = date(today.year, birth_date.month, birth_date.day)
if today > this_year_birthday:
# Birthday has already passed this year, so calculate for next year
next_birthday = date(today.year + 1, birth_date.month, birth_date.day)
else:
# Birthday is yet to come this year
next_birthday = this_year_birthday
days_left = (next_birthday - today).days
return days_left
def main():
"""Main function to run the Age Calculator with a continuous loop."""
print("--- Python Age Calculator ---")
while True:
print("\nEnter your birth date in YYYY-MM-DD format (or 'q' to quit).")
birth_date = get_valid_date_input("Enter your birth date: ")
if birth_date is None:
break
years, months, days = calculate_age(birth_date)
days_to_next_bday = days_until_next_birthday(birth_date)
print(f"\nYou are {years} years, {months} months, and {days} days old.")
if days_to_next_bday == 0:
print("Happy Birthday!")
else:
print(f"There are {days_to_next_bday} days until your next birthday.")
play_again = input("\nDo you want to calculate another age? (yes/no): ").strip().lower()
if play_again != 'yes':
print("Exiting Age Calculator. Goodbye!")
break
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()