Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent for a case/switch statement? [duplicate]

Is there a Python equivalent for the case statement such as the examples available in VB.NET or C#?

like image 370
John Alley Avatar asked Jul 14 '12 00:07

John Alley


People also ask

What is the replacement of switch case in Python?

What is the replacement of Switch Case in Python? Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.

Does Python have a switch statement?

Python does not have a switch statement functionality. But there are ways to replace the switch statement functionality and make the programming easier and faster. This is possible as Python allows us to create our code snippets that work like Switch case statements in any other language.

What is the alternative statement for switch case statement?

You could use a series of if else statements or you could lookup a set of values in a table. You could use an array of function pointers indexed by the character. But there's really no reason to use anything other than the switch statement.

Does Python have switch case statement True False?

A switch case statement is a multi-branched statement which compares the value of a variable to the values specified in the cases. Python does not have a switch statement but it can be implemented using other methods, which will be discussed below.


2 Answers

Python 3.10 and above

In Python 3.10, they introduced the pattern matching.

Example from the Python documentation:

def http_error(status):     match status:         case 400:             return "Bad request"         case 404:             return "Not found"         case 418:             return "I'm a teapot"         case _:             return "Something's wrong with the internet" 

Before Python 3.10

While the official documentation are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks def zero():     print "You typed zero.\n"  def sqr():     print "n is a perfect square\n"  def even():     print "n is an even number\n"  def prime():     print "n is a prime number\n"  # map the inputs to the function blocks options = {0 : zero,            1 : sqr,            4 : sqr,            9 : sqr,            2 : even,            3 : prime,            5 : prime,            7 : prime, } 

Then the equivalent switch block is invoked:

options[num]() 

This begins to fall apart if you heavily depend on fall through.

like image 77
Prashant Kumar Avatar answered Oct 12 '22 13:10

Prashant Kumar


The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

like image 26
Lennart Regebro Avatar answered Oct 12 '22 14:10

Lennart Regebro