user10777351
user10777351

Reputation:

How can I incorporate leap years in an age calculator?

I have made an age calculator in python that, after you answer a series of questions, gives you your age in years, months and days. I am trying to incorporate leap years in it using an if statement that adds an extra day onto your age for every leap year experience, but I think there could be a shorter way. Any ideas?

Here is my code:

currentDay = int(input('What day of the month is it?'))
currentMonth = int(input('What month is it?'))
currentYear = int(input('What year is it?'))
birthDay = int(input('What day of the month were you born on?'))
birthMonth = int(input('What month were you born?'))
birthYear = int(input('Which year were you born in?'))
ageDays = currentDay - birthDay
ageMonths = currentMonth - birthMonth
ageYears = currentYear - birthYear
daysToAdd = 0

if currentMonth == 1 or currentMonth == 3 or currentMonth == 5 or 
currentMonth == 7:
    daysToAdd = 31

elif currentMonth == 2:
    daysToAdd = 28

elif currentMonth == 8 or currentMonth == 10 or currentMonth == 12:
    daysToAdd = 31

else:
    daysToAdd = 30

if birthDay > currentDay:
    ageMonths = ageMonths + 1
    ageDays = ageDays + daysToAdd

if birthMonth > currentMonth:
    ageMonths = ageMonths + 12

if birthYear < 2016:
    ageDays = ageDays + 1
    if birthYear < 2012:
        ageDays = ageDays + 1
        if birthYear < 2008:
            ageDays = ageDays + 1
            if birthYear < 2004:
                ageDays = ageDays + 1
                if birthYear < 2000:
                    ageDays = ageDays + 1
                    if birthYear < 1996:
                        ageDays = ageDays + 1

print('You are: ', ageYears, ' years, ', ageMonths, ' months, ', ageDays, ' 
days.')

Upvotes: 0

Views: 1580

Answers (3)

Carlos Bettin
Carlos Bettin

Reputation: 130

Try this code:

# import date to get current year
from datetime import date
# Get current year
current_year = date.today().year
    # your code here...
    # ...
    # loop from birthYear to current year
    for y in range(birthYear, current_year+1, 1):
        # check if leap year
        if y in range(0, date.today().year, 4):
            ageDays = ageDays + 1

Hope it helps!

Upvotes: 0

Daweo
Daweo

Reputation: 36450

Leap years are defined as being divisible:

  • by 4 but not 100
  • by 400

Using list comprehension and range you can get number of leap years between given years following way:

start_year = 1998 #inclusive
end_year = 2019 #exclusive
leaps =  [i for i in list(range(start_year,end_year)) if (i%4==0 and i%100!=0) or i%400==0]
print(leaps)

output:

[2000, 2004, 2008, 2012, 2016]

Upvotes: 1

Tarifazo
Tarifazo

Reputation: 4343

Without using the said modules, assuming you are doing it for excercise sake, use integer division:

ageDays = ageDays + (2019-birthYear) // 4

Example:

(2019 - 2016) // 4
>> 0
(2019 - 2015) // 4
>> 1

Upvotes: 0

Related Questions