標籤:python switch
switch 文法結構:
switch 語句用於編寫多分支結構的程式,類似於if...elif...eles語句。
swtch 語句的表達的分支結果比if...elif...lese 語句表達的更清晰,代碼的可讀性更高。
####python並沒有提供switch語句######
但是:python 可以通過字典實現switch語句的功能。
實現方法:
定義一個字典
調用字典的get()擷取相應的運算式
範例:
>>> 6/41>>> 6.0/41.5>>> from __future__ import division>>> 5/22.5
# __future__模組 division 精確的除法
下面是一個計算機:
#!/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‘)
#注意三次判斷是多餘的,且如果符號錯誤,執行為空白,效率不是很好
如果通過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) #通過字典取值,省去判斷的環節;[[email protected] tools]# python switch.py 6<function jia at 0x7fc3ecb8fa28>7如果字典中沒有值或值是錯誤的:print operator["("](3,4)報錯如:Traceback (most recent call last): File "switch.py", line 20, in <module> print operator["("](3,4) KeyError: ‘(‘所以我們可以使用字典中get的方法: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
實現和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帶入函數中,類似如if的判斷
f(2,"-",4)
[[email protected] tools]# python switch.py
-2
本文出自 “思想大於技術” 部落格,謝絕轉載!
python 基礎學習 switch 語句