【发布时间】:2013-08-20 01:41:59
【问题描述】:
我一直在尝试找出一种方法来完成标题中的内容,而不使用从 Python 导入的任何日历/日期时间库。顶部几乎没有用于检查年份是否为闰年的功能,我希望在打印给定二月的天数时能够参考,但我不太确定如何这样做。 (我猜到了输出之类的东西。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'
好的,我已经修复了我的代码,它似乎每个月都输出正确的数据,但 2 月:
# 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
有什么提示可以修复二月份的输出吗?
编辑:只需要在引用第一个函数时添加参数年份。以下是 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
【问题讨论】:
-
elseif应该是elif -
Righto,解决了这个问题。此外,这是我在运行代码时遇到的错误代码,但我猜一旦对这个进行排序,还会有更多错误代码:def days_in_month(month, year): ^ IndentationError: unindent does not match any external缩进级别 .... ^ 应该在冒号上,只是不确定如何格式化此注释。
-
你可以通过写
if month in ('September', 'April', 'June', 'November'):来缩短它,因为它在一个函数中,你可能想要return计算的值而不是print它。 -
我把它缩短了一点并修复了一些东西,介意在 O.P 中检查我的第二批代码吗?似乎无法让二月份的分析发挥作用..
-
函数
is_leap_year需要参数year,你错过了
标签: python python-2.7 calendar days