Python multiple possibilities in if statement

Viewed 73

I am new to python and I have an assignment to print month names with corresponding numbers.

How can I make an if statement with multiple conditions so I don't need to make twelve of them?

Normally it would be :

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

Can I make it something like :

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

I tried it and it does not work, but I am wondering if it is possible?

2 Answers

You'd better save that in a dict, to get mappings month index -> month name

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

Or with calendar

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

Use Dictionary

months = {1:"Jan", 2:"Feb", 3:"March" ... and so on}

if inputMonth in months:
   print(months[inputMonth])

or you can use List

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