switch Syntax structure :
The switch statement is used to write a multi-branch structure program, similar to the If...elif...eles statement.
The branching result of the expression of the Swtch statement is clearer than the If...elif...lese statement, and the code is more readable.
# # # #python并没有提供switch语句 ######
However: Python can implement the switch statement functionality through a dictionary.
Implementation method:
Define a dictionary
Call the dictionary get () to get the appropriate expression
Example:
>>> 6/41>>> 6.0/41.5>>> from __future__ import division>>> 5/22.5
# __future__ Module Division precise Division
Here is a calculator:
#!/usr/bin/python#coding:utf-8from __future__ import divisiondef jia (x, y): return x+ydef jian (x, y): return x-ydef chu (x, y): return x/ydef cheng (x, y): return x*ydef operator (x,o,y): x =int (Raw_input ("plese somthing Number: ")) y =int (Raw_input (" Plese somthing number: ")) o = raw_input ("plese somthing +/*-:") if o == ' + ': print jia (x, y) elif o == ' * ': print cheng (x, y) elif o == '/': print chu (x, y) elif o == '-': print jian (x, y) else : passprint operator (' x ', ' o ', ' y ')
#注意三次判断是多余的, and if the symbol is wrong, execution is empty, the efficiency is not very good
If you write a calculator via switch
[[email protected] tools]# cat switch.py #!/usr/bin/python#coding:utf-8from __ Future__ import divisiondef jia (x, y): return x+ydef jian (x, y): return x-ydef chu (x, y): return x/ydef cheng (x, y): return x*yoperator = {"+": Jia, "-": Jian, "*": Cheng, "/": Chu}print jia (2,4) print jiaprint operator["+"] (3,4) #通过字典取值, eliminating the link of judgment; [[email protected] tools]# python switch.py 6<function jia at 0x7fc3ecb8fa28>7 if no value or value is wrong in the dictionary: print operator["("] (3,4) Error such as:traceback (Most recent call last): File "switch.py", line 20, in <module> print operator["(3,4) KeyError: ' (' So we can use the Get method in the dictionary:traceback (most recent call last): print operator.get["-"] (3,4 ) File "switch.py", line 21, in <module> print operator.get["-"] (3,4) typeerror: ' Builtin_function_or_method ' object is Unsubscriptable
Implement the same operation as if:
[email protected] tools]# cat switch.py
#!/usr/bin/python
#coding: Utf-8
From __future__ Import Division
def Jia (x, y):
Return X+y
Def Jian (x, y):
return x-y
def chu (x, y):
return x/Y
Def cheng (x, y):
Return X*y
operator = {"+": Jia, "-": Jian, "*": Cheng, "/": Chu}
def f (x,o,y):
Print Operator.get (o) (x, y) #将字典中的key带入函数中 similar to the If judgment
F (2, "-", 4)
[email protected] tools]# python switch.py
-2
This article from "thinking More than technology" blog, declined reprint!
Python Basic Learning switch statement