如何将leap年纳入年龄计算器?

时间:2019-01-29 20:15:58

标签: python if-statement

我用python制作了一个年龄计算器,在您回答了一系列问题之后,您可以以年,月和日为单位给您年龄。我正在尝试使用if语句将leap年纳入其中,以便为每个leap年经历增加一天的时间,但我认为可以采用更短的方法。有什么想法吗?

这是我的代码:

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.')

3 个答案:

答案 0 :(得分:0)

在不使用上述模块的情况下,假设您出于锻炼目的而使用整数除法:

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

示例:

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

答案 1 :(得分:0)

Le年的定义是可除的:

  • 4而不是100
  • 400分

使用list理解和range,您可以按照以下方式获得给定年份之间的of年数:

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)

输出:

[2000, 2004, 2008, 2012, 2016]

答案 2 :(得分:0)

尝试以下代码:

# 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

希望有帮助!

相关问题