我试图将一个数字分配给一年中的一个月,它应该使用if语句而不是字典



我正在努力迎接这个挑战:

设计函数month_name,它接受1到12之间的数字,并输出相应的月份名称。例如,给定数字2,函数应该打印二月。当给定一个无效数字时,你的函数不应该打印任何东西。函数应该使用if语句,不应该使用字典

到目前为止我只有这个:

# A month_name is a number -> string
# takes in a number and gives the coresponding month
def month_name(number1):
1 = January
2 = Febuary
3 = March
4 = April
5 = May
6 = June
7 = July 
8 = August
9 = Suptember
10 = October
11 = November
12 = December 

首先,您不应该为数字或保留关键字赋值。这适用于任何编程语言

Python已经有一个定义良好的库集。在这种情况下,我建议使用calendar

import calendar 
calendar.month_name(<month_number_here>)

如果你想冒险,可以使用列表或字典。

month_list = ['January', 'Febr......, 'December']

month_list = {1:January, 2:February, ...., 12:December}

如果列表索引从0开始查找month_list[<month_number_here> - 1]

字典查找month_list(<month_number_here>)

相关内容

最新更新