python并沒有提供switch語句!python可以通過字典實作switch語句的功能。
1)首先,定義一個字典;
#!/usr/bin/python
#coding:utf8
from __future__ import division#使除非操作自動識别小數結果
def jia(x,y):
return x+y
def jian(x,y):
return x-y
def cheng(x,y):
return x*y
def chu(x,y):
return x/y
operator = {"+":jia,"-":jian,"*":cheng,"/":chu}
print operator["/"](3,2)
def f(x,o,y):
print operator.get(o)(x,y)#類似switch函數操作
f(3,"/",2)#函數調用