The Python language has no switch-case statements __python

Source: Internet
Author: User
Learning the Python language, it took a long time to find that Python does not have switch-case statements, view the official document that can be used if-elseif-elseif .... Replace.

Truth be told, none of this is a problem. is not a condition to judge it. -....... with If-elseif Certainly no problem, but also with other solutions, relatively simple is to use

Dictionary to achieve the same function. Write a dictionary, each key corresponds to a value is a method. such as switch = {"Valuea": Functiona, "Valueb": functionb, "VALUEC": Functionc}

Call can be like this

Try

switch["value"] () #执行相应的方法.

Except Keyerror as E:

Pass or Functionx #执行default部分

The simple code is as follows:

1 switch = {
 2     "a": Lambda x:x*2,
 3     "B": Lambda x:x*3,
 4     "C": Lambda x:x**x
 5}
 6 
 7 Try:
 8     swtich["C"] (6)
 9 except Keyerror as E:     

It's no problem if you don't bother writing a swtich class to achieve it. But is that really necessary?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.