There is no switch in python

Postscript (2014/2/6)


I like switch statements. The outlook for the program is much better and your mind is tidied up. However, there is no switch statement in python. The major is to use if, elif, etc. for conditional branching. For example, if there is a switch statement like the one below,

#General switch statement used in java etc.
switch(str){
case 'a':
case 'b':
    print('a,b'); break;
case 'c': 
    print('c'); break;
}

In python, using if and elif, it looks like this:

if str == 'a' or str == 'b':
    print('a,b')
elif str == 'c':
    print('c')

Writing str == twice in the first if statement can be tedious. In particular, if there are two or more of these, or if the variable name is long, the if statement will be long and the readability of the program will be reduced. Therefore,

if str in {'a', 'b'}:
    print('a, b')
elif str == 'c':
    print('c')

Then the outlook will be better. You can reaffirm that python's in is useful.

Recommended Posts

There is no switch in python
Python virtual environment in 2021 ~ There is no reason not to use venv now ~
Difference between == and is in python
Is there a special in scipy? ??
Python is UnicodeEncodeError in CodeBox docker
When "No changes detected" is displayed in python3 manage.py makemigrations
Python in is also an operator
What to do when there is no response due to Proxy setting in Python web scraping
There is no eclipse project description file (.project).
"<" In python> pack ("<L", ...) is little endian
Inject is recommended for DDD in Python
Revived from "no internet access" in Python
In python + sqlite3 "OperationalError: no such column:"
What is "mahjong" in the Python library? ??
Hash in Perl is a dictionary in Python
How to switch python versions in cloud9
ModuleNotFoundError in Python: No module named story
How to use is and == in Python
Import Error in Python3: No module named'xxxxx'
There is no telnet! At that time
Is there NaN in the pandas DataFrame?
Quadtree in Python --2
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
What to do if there is a decimal in python json .dumps
Python is easy
Meta-analysis in Python
Unittest in python
Discord in Python
Switch Python versions
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Note that Python dict returns default value if there is no key
Plink in Python
Constant in python
What is python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
When issuing an INSERT statement in Python, no such column is displayed
N-gram in python
LINE-Bot [0] in Python
Python is instance
Csv in python
Disassemble in Python
Reflection in Python
There is Linux.
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python