5.python Grammar Basic-switch structure

Source: Internet
Author: User
Tags mul

Description
    1.switch is clearer and more readable than if...else statements
    2.python does not provide a switch statement 3.pthon uses a dictionary to implement the switch statement function, the implementation method is divided into 2 steps:
A. Define a dictionary;B. Call the dictionary get () to get the corresponding expressionPython code:
  
 
  1. def add(x,y):
  2. return x+y
  3. def sub(x,y):
  4. return x-y
  5. def mul(x,y):
  6. return x*y
  7. def div(x,y):
  8. return x/y
  9. operation={‘+‘:add,‘-‘:sub,‘*‘:mul,‘/‘:div} #用字典方法存不同类型运算符
  10. def result(x,o,y):
  11. print operation.get(o)(x,y) #使用get(o)等价于字典中的操作符+-*/对应的键值value即函数
  12. result(10, ‘-‘, 3) #调用函数,验证结果,在中间传什么操作符做什么操作,比起if来程序效率高
Note: The use of a dictionary-processed switch statement is less than if...else processing, which improves the efficiency of the program.


From for notes (Wiz)

5.python Grammar Basic-switch structure

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.