面向学生的跨年度python任务

面向学生的跨年度python任务,python,leap-year,Python,Leap Year,向yr10教授python的新手。当告诉最终用户他们的年份是否是闰年时,这似乎起作用。但是有人能确认一下这个代码是否有效,或者是最好的方法。我意识到可能有不同的方法…约翰尼: leapYear = int(input("what year is it?:")) if (leapYear %4) == 0: print ("Thats a leap year") elif (leapYear %100)==0: print ("thats not a leap year")

向yr10教授python的新手。当告诉最终用户他们的年份是否是闰年时,这似乎起作用。但是有人能确认一下这个代码是否有效,或者是最好的方法。我意识到可能有不同的方法…约翰尼:

leapYear = int(input("what year is it?:"))

if (leapYear %4) == 0:
    print ("Thats a leap year")

elif (leapYear %100)==0:
    print ("thats not a leap year")

elif (leapYear % 400)== 0:
        print ("Thats a leap year")

else:
    print("thats not a leap year")

这里有三种在python中检查闰年的替代方法,第二种方法是您自己尝试的改进版本:

1使用:

2与您自己的尝试类似,但去掉多余的步骤并将其转换为方法:

3使用以下方法检查所提供年份是否具有2月29日:


注意:试着教你的学生在python代码中使用,而不是。

检查代码是否正常工作的最好方法是测试代码。使用所有类型的输入运行它,并检查它是否给出了正确的答案。如果代码有逻辑错误,它将错误地将100标识为闰年。你需要考虑你评估你的条件的顺序,例如,如果LeAPe= 400,那么它符合所有的条件,哪一个应该被首先评估?我认为你的ELIFs是多余的。如果你在教编程,你可能会对它感兴趣,因为它仍然是私人测试版,在这里输入是最容易的
import calendar

calendar.isleap(year)
def is_leap_year(year):
    if year % 100 == 0:
        return year % 400 == 0
    return year % 4 == 0
import datetime

def is_leap_year(year):
    try:
        datetime.date(year, 2, 29)
    except ValueError:
        return False
    return True