Does python have a switch statement?

anonymity
Release: 2019-06-14 09:51:30
Original
18590 people have browsed it

Python does not have a switch-case statement. The official documentation states that it can be replaced by if-elseif-elseif.

Does python have a switch statement?

#Also use other solutions, the simpler one is to use a dictionary to achieve the same function. Write a dictionary, and the value corresponding to each key is a method.

For example, switch = {"valueA":functionA,"valueB":functionB,"valueC":functionC}

When calling, it can be like this

try:
  switch["value"]() #执行相应的方法。
except KeyError as e:
  pass 或 functionX #执行default部分
Copy after login

The simple code is as follows:

switch = {
    "a":lambda x:x*2,
    "b":lambda x:x*3,
    "c":lambda x:x**x
}
try:
    swtich["c"](6)
except KeyError as e:
    pass
Copy after login

You can also write a swtich class yourself to implement the function

The above is the detailed content of Does python have a switch statement?. 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
Popular Tutorials
More>
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!