Home > Net >  Pyhon multiple possibilities in if statment
Pyhon multiple possibilities in if statment

Time:11-21

Can I make one if statement with more options so I don't need to make twelve of them? I am new to python and I have an assignment to print month names with corresponding numbers. 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?

CodePudding user response:

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])

CodePudding user response:

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