What to use instead of switch in Python

Release: 2019-07-06 09:01:53
Original
3606 people have browsed it

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 不同时执行的代码 }'''
Copy after login

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"}'''
Copy after login

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)
Copy after login

A simpler way The best way is to use lambda.

For more Python related technical articles, please visit thePython Tutorialcolumn 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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!