Python 我试图分配一个数字到一年中的一个月,它应该使用if语句,而不是dicinaries
我正在应对这一挑战: 设计函数month_name,该函数采用1到12之间的数字,并打印相应的月份名称。例如,给定数字2,函数应在2月份打印。当给定一个无效数字时,函数不应该打印任何内容。函数应该使用if语句,而不应该使用字典 到目前为止,我只有这个:Python 我试图分配一个数字到一年中的一个月,它应该使用if语句,而不是dicinaries,python,Python,我正在应对这一挑战: 设计函数month_name,该函数采用1到12之间的数字,并打印相应的月份名称。例如,给定数字2,函数应在2月份打印。当给定一个无效数字时,函数不应该打印任何内容。函数应该使用if语句,而不应该使用字典 到目前为止,我只有这个: # A month_name is a number -> string # takes in a number and gives the coresponding month def month_name(number1): 1
# 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已经有了一套定义良好的库。在这种情况下,我建议使用日历
import calendar
calendar.month_name(<month_number_here>)
或
如果列表索引从0开始
所以查找month\u列表[-1]
在字典查找的情况下,
month\u list()。这不是有效的Python:您不能分配给数字文本。您不使用函数的参数。
month_list = ['January', 'Febr......, 'December']
month_list = {1:January, 2:February, ...., 12:December}