Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have an equivalent to 'switch'?

I am trying to check each index in an 8 digit binary string. If it is '0' then it is 'OFF' otherwise it is 'ON'.

Is there a more concise way to write this code with a switch-like feature?

like image 406
AME Avatar asked Sep 15 '09 20:09

AME


People also ask

What is Python equivalent of switch?

Pattern matching is the switch-case equivalent in Python 3.10 and newer. A pattern matching statement starts with the match keyword, and it contains one or more case blocks.

Does Python have a switch function?

Unlike any other programming language, python language does not have switch statement functionality.

Why doesn't Python have a switch?

Python doesn't have a switch/case statement because of Unsatisfactory Proposals . Nobody has been able to suggest an implementation that works well with Python's syntax and established coding style.

Is Switch Case available in Python?

From version 3.10 upwards, Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords.


2 Answers

No, it doesn't. When it comes to the language itself, one of the core Python principles is to only have one way to do something. The switch is redundant to:

if x == 1:     pass elif x == 5:     pass elif x == 10:     pass 

(without the fall-through, of course).

The switch was originally introduced as a compiler optimization for C. Modern compilers no longer need these hints to optimize this sort of logic statement.

like image 171
Soviut Avatar answered Oct 04 '22 23:10

Soviut


Try this instead:

def on_function(*args, **kwargs):     # do something  def off_function(*args, **kwargs):     # do something  function_dict = { '0' : off_function, '1' : on_function }  for ch in binary_string:    function_dict[ch]() 

Or you could use a list comprehension or generator expression if your functions return values:

result_list = [function_dict[ch]() for ch in binary_string] 
like image 44
Jeff Avatar answered Oct 04 '22 23:10

Jeff