There is no switch in Python, so sometimes we need to use switch to do so only through if else. But if else writes more verbose,
This can be accomplished using Python's dict, which is more concise than switch. Use the following:
If it is the case of key1 execution func1, if it is key2 the case of the implementation of FUNC2 ... (Func1, Func2 ... All functions must have the same Parameter form),
Assume that each function parameter is (ARG1, arg2):
Dictname = {"key1""key2" "key3": Func3"...} #字典的值直接是函数的名字, cannot be quoted Dictname[key] (arg1, arg2)
Example The code is as follows:
#!/usr/bin/python#File:switchDict.py#Author:lxw#time:2014/10/05ImportRedefAdd (x, y):returnX +ydefSub (x, y):returnX-ydefmul (x, y):returnX *ydefDiv (x, y):returnX/ydefMain (): InStr= Raw_input ("Please input the easy expression: (e.g. 1 + 2.But 1 + 2 + 3 is not accepted.\n") Inlist= Re.split ("(\w+)", inStr) inlist[1] = inlist[1].strip ()Print("-------------------------") Print(inlist)Print("-------------------------") #Method 1: ifINLIST[1] = ="+": Print(Add (int (inlist[0]), int (inlist[2]))) elifINLIST[1] = ="-": Print(Sub (int (inlist[0]), int (inlist[2]))) elifINLIST[1] = ="*": Print(Mul (int (inlist[0]), int (inlist[2]))) elifINLIST[1] = ="/": Print(Div (int (inlist[0]), int (inlist[2]))) Else: Pass #Method 2: Try: operator= {"+": Add,"-": Sub,"*": Mul,"/":d IV}Print(Operator[inlist[1]] (int (inlist[0)), int (inlist[2]))) exceptKeyerror:Passif __name__=='__main__': Main ()
Output:
PS j:\>python. \switchdict.pyplease input the easy expression: (e.g.1 + 2.But 1 + 2 + 3 are notaccepted.1 + 2-------------------------['1','+','2']-------------------------33PS j:\>python. \switchdict.pyplease input the easy expression: (e.g.1 + 2.But 1 + 2 + 3 are notaccepted.4-9-------------------------['4','-','9']--------------------------5-5PS j:\>python. \switchdict.pyplease input the easy expression: (e.g.1 + 2.But 1 + 2 + 3 are notaccepted.6/5-------------------------['6','/','5']-------------------------11PS j:\>python. \switchdict.pyplease input the easy expression: (e.g.1 + 2.But 1 + 2 + 3 are notaccepted.1 9 9-------------------------['1',"','9',' ','9']-------------------------PS j:\>python. \switchdict.pyplease input the easy expression: (e.g.1 + 2.But 1 + 2 + 3 are notaccepted.1 (9-------------------------['1','(','9']-------------------------PS j:\>
Personal feeling, if you want to use switch to solve a problem, and the actions in each case are the same in form (such as executing a function and these functions have
The same parameters), it can be implemented in this way.
Python function Masterpiece is a dictionary value