将日历功能用于leap年

时间:2019-10-08 04:41:47

标签: python python-import leap-year

我正在尝试使用导入功能来计算my年,但是我收到的代码错误消息:

import calendar
year=input("Enter a year: ")
check=calendar.isleap(year)
if check == True:
    print("In",year,"February has 29 days.")
else:
    print("In",year,"February has 28 days.")

如果有人能在这里指出我的错误,将不胜感激!

我也尝试过

return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

使用'if-else'语句的方法,但似乎也偶然发现使用该方法的障碍...该方法的代码如下所示:

print ('hi')
input_year= input("Please enter a year: ")
if (input_year) % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print ("Yes sir")
else:
    print ("no sir")

1 个答案:

答案 0 :(得分:0)

Python 2将自动尝试将用户键入的字符串转换为数字,并尽可能地从input函数返回一个整数。但是Python 3会更加一致,即使逻辑上将用户键入的字符理解为数字,也总是返回 string

因此,请执行以下操作:

import calendar
year=input("Enter a year: ")
year = int(year)
check=calendar.isleap(year)
if check:
    print("In",year,"February has 29 days.")
else:
    print("In",year,"February has 28 days.")