gpt4 book ai didi

python - 打印给定月份和年份的天数 [Python]

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:52 24 4
gpt4 key购买 nike

我一直在尝试找到一种方法来完成标题中的内容,而不使用任何从 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

最佳答案

一种更像 Python 的方法是在字典中定义映射,然后简单地从字典中检索值。

尝试一下:

days_in_month_dict = {"January": 31, "February": 28, 
"March": 31, "April": 30,
"May": 31, "June": 30,
"July": 31, "August": 31,
"September": 30, "October": 31,
"November": 30, "December": 31}

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

def days_in_month(year, month):
if is_leap_year(year) and month == "February":
return 28

try:
#attempt to get value from dictionary
return days_in_month_dict[month]
except KeyError:
#key does not exist, so we caught the error
return None

关于python - 打印给定月份和年份的天数 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18325705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com