如何计算闰年的天数



>编写一个程序,提示用户输入月份和年份,然后将消息输出到说明给定月份有多少天(注意:如果用户进入月份的二月)

我在第一个 int 中使用并输入月份和年份

如果 (year/400 == 0) 和 (year/100 != 0) 或 (year/4 == 0):

print( "this year is a leap year: ")
if ( month == "December" or  month == "January" or month == "March" or  month == "May" or month  == "July" or  month == "August" or month == "October" ):
    print ("days are: 31")
elif ( month == "April" or month == "June" or month == "September" or  month == "November"):
    print ("days are: 30")
elif ( month == "February" ):
    print ("days are: 29")

还:

print( "this year is not a leap year: ")
if ( month == "December" or  month == "January" or month == "March" or  month == "May" or month == "July" or  month == "August" or month == "October" ):
    print ("days are: 31")
elif ( month == "April" or month == "June" or month == "September" or  month == "November"):
    print ("days are: 30")
elif ( month == "February" ):
    print ("days are: 28")

代码不正确,它只能与其他代码一起使用,所以如果有人对错误有想法我认为第一个条件下的错误(如果年份/400 == 0).......

你可以使用内置模块日历中的 isleap() 函数。

import calendar
print (calendar.isleap(1900))

打印False,因为 1900 年不是闰年。

使用如下帮助程序函数:

def is_leap(n): 
    if n % 400 == 0:
        return True
    if n % 100 == 0:
        return False
    if n % 4 == 0:
        return True
    else:
        return False
if is_leap(year):
    #your code
def is_year_leap(year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
def days_in_month(year, month):
    list_31 = [1,3,5,7,8,10,12]
    list_30 = [4,6,9,11]
    if month in list_31 :
        return 31
    elif month in list_30 :
        return 30
    elif is_year_leap(year) and month == 2:
        return 29
    # elif is_year_leap(year) != True and month == 2:
    else:
        return 28

x = int(input('Enter any year: '))
y  = int(input('Enter a month: '))

l_p = is_year_leap(x)
month_in_lp = days_in_month(x,y)
print(l_p, month_in_lp)

看看年份是否可以被 4 整除。如果是这样,那就是闰年。

if not year % 4:
    leap_year = True

最新更新