Home  >  Article  >  Backend Development  >  What to use instead of switch in Python

What to use instead of switch in Python

尚
Original
2019-07-02 11:43:553659browse

What to use instead of switch in Python

Switch needs to be used in the program. I checked and found that there is no such syntax in python. After reading the official documentation, I found out that the official recommendation is to use if..elif...else to replace. If there are too many categories, the official recommendation is to construct a dictionary mapping in the function and then call function(value) to solve it.

switch statement:

'''switch(n)
{case 1:
  执行代码块 1
  break;case 2:
  执行代码块 2
  break;default:
  n 与 case 1 和 case 2 不同时执行的代码
}'''

Example:

'''switch (day)
{case 0:
    x="Today it's Sunday";
    break;
 case 1:
    x="Today it's Monday";
    break;
 case 2:
    x="Today it's Tuesday";
    break;
 case 3:
    x="unknown"}'''

Dictionary method in Python:

day = 3
switcher = {
    0:'Today it\'s Sunday',
    1:'Today it\'s Monday',
    2:'Today it\'s Tuesday'
}
#day_name =switcher[day]  #并不能显示default
day_name = switcher.get(day,'Unknown')
print(day_name)

A simpler way The best way is to use lambda.

For more Python related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of What to use instead of switch in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn