def YearType(year):
leapyear = False
year = int(year)
if year MOD 4 == 0 or year MOD 400 == 0:
leapyear = True
elif (year MOD 100 == 0):
leapyear = False
elif leapyear == True:
print("wow this year is a leap year!")
else:
print("this isnt a leap year :(")
print YearType(2000)
这里有几个问题:
- 算法:
1900 MOD 4 == 0
,但1900
是不是闰年 语法:Python使用 - 逻辑:
elif leapyear == True:
应该是if leapyear == True:
%
而不是MOD
代码:
# Business Logics
if year % 400 == 0: # 1600, 2000, 2400 are leap years
leapyear = True
elif (year % 100 == 0): # 1800, 1900, 2100 are not leap years
leapyear = False
elif (year % 4 == 0): # 1996, 2004, 2008, 2012, 2020 are leap years
leapyear = True
else:
leapyear = False # 2018, 2019, 2021 are not leap years
# UI
if leapyear:
print("wow this year is a leap year!")
else:
print("this isnt a leap year :(")
编辑:如果你想实现一个功能,我建议把它分成两部分:业务逻辑和UI:
def IsLeapYear(year):
if year % 400 == 0:
return True
elif (year % 100 == 0):
return False
elif (year % 4 == 0):
return True
else:
return False
def YearType(year):
if (IsLeapYear(year)):
print("wow this year is a leap year!")
else:
print("this isnt a leap year :(")
print(YearType(2000))