Is there a way to shorten if-elif-else statement in python?

I am just started to learn python and I did some code with an if statement and I think there are too many elif statements in the code so I was wondering if there is any way I can shorten the code.

from random import *
month = randrange(1, 13)
if month == 1:
    print("January")
elif month == 2:
    print("February")
elif month == 3:
    print("March")
elif month == 4:
    print("April")
elif month == 5:
    print("May")
elif month == 6:
    print("June")
elif month == 7:
    print("July")
elif month == 8:
    print("August")
elif month == 9:
   print("September")
elif month == 10:
   print("October")
elif month == 11:
    print("November")
else:
    print("December")

4 answers

  • answered 2021-09-11 18:12 StuCode

    For this case you could create a dictionary with the key being the number and value as the text. There is no built in switch case in python if that is what you are looking for

  • answered 2021-09-11 18:12 Patrick Artner

    Use a lookup dictionary instead:

    month_lu = { 1:"January", 2:"February", 3:"March" ) # etc
    
    m = randrange(1, 3)  # got 2
    print( month_lu[m] )
    

    Output:

    February
    

    Or use a random from a iteratble tuple / list of months names to begin with:

    month = random.choice( ( "Jan","Feb","Mar","Apr") ) # etc
    

    You choose the month directly, without first drawing a number.


    If you are really lazy, use the calendar module to provide names:

    import random
    import calendar
    
    months = list(calendar.month_name)
    
    print(random.choice(months))
    

    Output:

    October
    

  • answered 2021-09-11 18:14 Mureinik

    You could put the months in a list and access it via a random index:

    from random import *
    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'Augsut', 'September', 'October', 'November', 'December']
    month = randrange(12)
    return months[month]
    

  • answered 2021-09-11 18:23 Alex SHP

    Wait until Python 3.10, where match-case statements are being introduced.

    Here's an example :

    def sign_as_string(x:int)->str:
        """Returns the sign of x as a string. 
        A quick example that implements 3.10 syntax"""
        match x:
            case 0 :
                return "null"
            case y if y > 0:
                return "pos"
            case _ :
                return "neg"
    
    print(sign_as_sign( 1 )) //pos
    print(sign_as_sign(-1 )) //neg
    print(sign_as_sign( 0 )) //null
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum