簡體   English   中英

如何將leap年納入年齡計算器?

[英]How can I incorporate leap years in an age calculator?

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

在不使用上述模塊的情況下,假設您出於鍛煉目的而使用整數除法:

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

例:

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

years年被定義為可整除的:

  • 4而不是100
  • 400

使用list理解和range您可以通過以下方式獲得給定年份之間的leap年數:

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]

試試這個代碼:

# 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

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM