为了账号安全,请及时绑定邮箱和手机立即绑定

想要在 python 中显示月份名称和闰年

想要在 python 中显示月份名称和闰年

jeck猫 2023-09-26 16:45:46
程序应提示用户输入月份和年份(作为整数)并显示该月的天数以及月份名称。例如,如果用户输入 2 月和 2000 年,程序应显示:Enter a month as an integer (1-12): 2Enter a year: 2000There are 29 days in February of 2000def numberOfDays(month, year):    daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]    if month > len(daysInMonths) or year < 0 or month < 0:        return "Please enter a valid month/year"    return daysInMonths[month-1] + int((year % 4) == 0 and month == 2)def main():    year = int(input("Enter a year: "))    month = int(input("Enter a month in terms of a number: "))    print(month, year, "has", numberOfDays(month, year) , "days")if __name__ == '__main__':     main()在这个程序中,我想显示月份的名称并将其打印在最后。那么程序会怎样呢?我应该怎么办?例如,如果输入为 1,则 1 应指定为一月并打印。
查看完整描述

2 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

使用字典:


dict_month = {1:"January", 2: "February"} # and so on ...


print(dict_month.get(month), year, "has", numberOfDays(month, year) , "days")


查看完整回答
反对 回复 2023-09-26
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

您可以使用日历模块来完成此任务:


import calendar

months = list(calendar.month_name) #gets the list of months by name

obj = calendar.Calendar()


y, m = int(input('Enter year: ')), int(input('Enter a month as an integer (1-12): '))

days = calendar.monthrange(y, m)[1]


print(f'There are {days} days in {months[m]} of {y}')

如果您只想检查年份是否为闰年:


import calendar

print(calendar.isleap(int(input('Enter year: '))))


查看完整回答
反对 回复 2023-09-26
  • 2 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信