我一直在尝试找出一种方法来完成标题中的内容,而不使用任何从 Python 导入的日历/日期时间库。顶部几乎没有用于检查年份是否为闰年的功能,我希望在打印给定二月的天数时能够参考这一点,但我不太确定该怎么做。 (我猜到了类似 output.bla bla 的东西)
到目前为止,我已经想出了这样的事情,这应该清楚我想做什么,但我对 Python 还是有点陌生,所以我会喜欢一些提示/帮助来修复我的任务代码.
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month == 'September' or month == 'April' or month == 'June' or month == 'November'
print 30
elseif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'\
or month== 'December'
print 31
elseif month == 'February' and output.is_leap_year = True
print 29
elseif month == 'February' and output.is_leap_year = False
print 28
else print 'Blank'
好的,我已经修复了我的代码,它似乎每个月都输出正确的数据,但二月除外:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month in ['September', 'April', 'June', 'November']:
print 30
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print 31
elif month == 'February' and is_leap_year == True:
print 29
elif month == 'February' and is_leap_year == False:
print 28
有什么提示可以解决 2 月的输出问题吗?
编辑:只需要在引用第一个函数时添加参数年份。这是供将来参考的 100% 工作代码:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year(year):
return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)
# You should complete the definition of this function:
def days_in_month(month, year):
if month in ['September', 'April', 'June', 'November']:
print 30
elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
print 31
elif month == 'February' and is_leap_year(year) == True:
print 29
elif month == 'February' and is_leap_year(year) == False:
print 28
else:
return None
的
的
的
原文由 James Adams 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码中存在一些语法错误:
def days_in_month(month,year)
之前不应有空格。 Python 使用缩进来分隔代码块。这是您在评论中给出的错误。elseif
,应该是elif
output.is_leap_year = True
,应该是is_leap_year(year) == True
。False
部分也应该改变。if
声明和else
之后应该有一个:
,就像