Home  >  Article  >  Backend Development  >  Does python have a switch statement?

Does python have a switch statement?

anonymity
anonymityOriginal
2019-06-12 14:45:5218593browse

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部分

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

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!

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