Step Into Python World (vi) Process Control 2. Branch Control (Swith)

Source: Internet
Author: User

In most programming languages, there are branch control statement switch.

The switch statement is used to write a multi-branch structure program, similar to the If...elif...else statement

The branching structure expressed by the Swith statement is clearer than the If...elif...else statement, and the code is more readable.

But Python does not provide a switch statement

The switch implementation in Python

Python can implement the switch statement function through a dictionary

The implementation method is divided into two cloth

First, define a dictionary

Second, get the corresponding expression using the get () of the dictionary


Function call

Calling a function from a dictionary, returning the corresponding value

{1:case1,2:case}.get (X,lambda*args,**key:) ()
From __future__ Import Division # # #引入除法模块def Jia (x, y): Return x+ydef Jian (x, y): Return x-ydef cheng (x, y): return X*ydef Chu (x, y): return x/y operator = {"+": Jia, "-": Jian, "*", Cheng, "/": Chu}print Chu ##### Printing method object Print operator["/" ] (3,2) ###### print out 1.5print operator["("] (3.2) ###### error, no key value (Def f (x,o,y): Print Operator.get (o) (x, y) print Opera Tor.get (0) (X,y,*args,**kwargs) F (3, "+", 2) # # # # # # # # Print out 5


Step Into Python World (vi) Process Control 2. Branch Control (Swith)

Related Article

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.