Replacements for switch statement in Python

Python switch statement replacement: Here, we are going to learn about the replacements for switch statement in Python?
Submitted by Sapna Deraje Radhakrishna, on January 19, 2020

Python doesn't provide a built-in switch statement, unlike other programming languages.

But there are scenarios, for which, using a switch statement is more optimized. To benefit ourselves to use a switch case, the following are the work-around.

Consider the below example, of switch case in Java

public static String switchCase(int monthNum) {
    String monthName = "Invalid Month";
    switch (monthNum) {
        case 1:
            monthName = "January";
            break;
        case 2:
            monthName = "February";
            break;
        case 3:
            monthName = "March";
            break;
        case 4:
            monthName = "April";
            break;
        case 5:
            monthName = "May";
            break;
        case 6:
            monthName = "June";
            break;
        case 7:
            monthName = "July";
            break;
        case 8:
            monthName = "August";
            break;
        case 9:
            monthName = "September";
            break;
        case 10:
            monthName = "October";
            break;
        case 11:
            monthName = "November";
            break;
        case 12:
            monthName = "December";
            break;
        default:
            monthName = "Please provide the month number";
    }
    return monthName;
}

Now, by using the dictionary in python, we will be able to replicate similar behavior.

def month(i):
	switch={
		1:'January',
		2:'February',
		3:'March',
		4:'April',
		5:'May',
		6:'June',
		7:'July',
		8:'August',
		9:'September',
		10:'October',
		11:'November',
		12:'December'
	}
	return switch.get(i, "Invalid month")

# printing
print(month(12))
print(month(13))

Output

December
Invalid month

In the above for values other than the ones mentioned in the switch, the code prints out "Invalid day of week". This is because we tell it to do so using the get() method of a dictionary.

Python Tutorial


ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.