Age Calculator |
Here is a simple script for an age calculator program in Python:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import date | |
def calculate_age(birth_year, birth_month, birth_day): | |
today = date.today() | |
age = today.year - birth_year - ((today.month, today.day) < (birth_month, birth_day)) | |
return age | |
birth_year = int(input("Enter your birth year: ")) | |
birth_month = int(input("Enter your birth month (1-12): ")) | |
birth_day = int(input("Enter your birth day (1-31): ")) | |
age = calculate_age(birth_year, birth_month, birth_day) | |
print("You are", age, "years old.") |
This script prompts the user to enter their birth year, month, and day, and then uses the calculate_age() function to calculate the user's age based on the current date. The calculate_age() function takes in the birth year, month, and day as arguments, and returns the age as an integer.
Alternatively, you can use the date of birth as input and calculate the current date in the function:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
def calculate_age(birth_date): | |
today = datetime.datetime.now() | |
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day)) | |
return age | |
birth_date = input("Enter your birth date(yyyy-mm-dd): ") | |
birth_date = datetime.datetime.strptime(birth_date, "%Y-%m-%d").date() | |
age = calculate_age(birth_date) | |
print("You are", age, "years old.") |
It will work the same as the previous one, but you don't need to input year, month, and day separately.