我可以做一個if有更多選項的陳述,這樣我就不需要做出 12 個選項嗎?我是 python 的新手,我有一個任務來列印帶有相應數字的月份名稱。通常它會是:
if month == 1
print(one) # one = January
我可以讓它像:
if month == [1,2,3,4,5,6]
print [one,two.three, etc.]
我試過了,它不起作用,但我想知道這是否可能?
uj5u.com熱心網友回復:
你最好把它保存在一個字典中,以獲得映射 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])
uj5u.com熱心網友回復:
使用字典
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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362769.html
