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

程序应提示用户输入月份和年份(作为整数)并显示该月的天数以及月份名称。例如,如果用户输入 2 月和 2000 年,程序应显示:


Enter a month as an integer (1-12): 2

Enter a year: 2000

There are 29 days in February of 2000

def 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 应指定为一月并打印。


jeck猫
浏览 86回答 2
2回答

海绵宝宝撒

使用字典:dict_month = {1:"January", 2: "February"} # and so on ...print(dict_month.get(month), year, "has", numberOfDays(month, year) , "days")

饮歌长啸

您可以使用日历模块来完成此任务:import calendarmonths = list(calendar.month_name) #gets the list of months by nameobj = 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 calendarprint(calendar.isleap(int(input('Enter year: '))))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python