×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Replacement for switch statement in Python

By IncludeHelp Last updated : December 08, 2024

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

The switch statement in other programming

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;
}

The switch statement in Python (Replacement)

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

Example

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.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.