Python在if语句中有多种可能性



我是python的新手,我有一项任务要打印带有相应数字的月份名称。

如何在多个条件下生成if语句,这样就不需要生成其中的十二个条件?

通常情况下是:

if month == 1
print(one) # one = January

我能把它做成这样吗:

if month == [1,2,3,4,5,6]
print [one,two.three, etc.]

我试过了,但不起作用,但我想知道这是否可能?

您最好将其保存在dict中,以获得映射month index -> month name

months = {1: "January", 2: "February"}
month = 1
if month in months:
print(months[month])

或使用calendar

import calendar
month = 1
if month in range(13):
print(calendar.month_name[month])

使用字典

months = {1:"Jan", 2:"Feb", 3:"March" ... and so on}
if inputMonth in months:
print(months[inputMonth])

或者你可以使用列表

months = ["Jan", "Feb", "March"... ]
inputMonth = 1
if inputMonth in range(0,13):
print(months[inputMonth-1])

最新更新