Python uses dict to mimic switch statement functionality

Source: Internet
Author: User

Python itself does not provide a switch syntax, and in order to solve problems like switch branch requirements, we can use dictionaries instead of implementations.
Solution Ideas:

    1. Handle the default in a switch statement using the fault tolerance of the Get method of the dictionary value
    2. Set the Vlaue of the dictionary to the corresponding method name instead of the code block in the switch statement
    3. Set the same value for different keys to simulate a switch that penetrates
DefTaskforsunday(): Print ("Rest Today")DefTaskforrest(): Print ("Rest Today")DefTaskforchinese(): Print ("Today's Chinese Class")def taskformath (): print ( "Today's math Class") def taskforenglish (): print ( "English class Today") Span class= "hljs-function" >def taskfordefault (): print (" input error .... ") Switchdic = {" Sunday ": Taskforrest, " Monday ": Taskforchinese,  "Tuesday": Taskformath,  "Wednesday": Taskforenglish,  "Tursday": Taskforenglish,  "Friday": Taskforenglish, " Saturday ": taskforrest}           

1. Test values

After getting the method of the dictionary key corresponding to the get, the parentheses are added so that the resulting method will be executed.

"Monday"switchDic.get(day1,taskForDefault)() #打印:今天上语文课

2. Test penetration
##Wednesday,Tursday,Friday三个的效果相同day2 = "Friday"switchDic.get(day2,taskForDefault)()  #打印:今天上英语课

3. Test Deault Effect
#字典的get方法第二个参数是默认值,即通过key值不能找到value时,返回默认值#这里使用了自定义函数的函数名:taskForDefault,用于实现switch的defalut功能day3 = "天气不错哦"switchDic.get(day3,taskForDefault)() #打印:输入错误啦。。。。

Python uses dict to mimic switch statement functionality

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.