说明:
1,实现switch的一般方式
from __future__ import division
def add(x, y) :
return x + y
def subtract(x, y) :
return x - y
def multiply(x, y) :
return x * y
def divide(x, y) :
return x / y
def calculate(x, y, symbol) :
if "+" == symbol :
print add(x, y)
elif "-" == symbol :
print subtract(x, y)
elif "*" == symbol :
print multiply(x, y)
elif "/" == symbol :
print divide(x, y)
else :
pass
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
2,字典实现switch语句
- value 为 函数
from __future__ import division
def add(x, y) :
return x + y
def subtract(x, y) :
return x - y
def multiply(x, y) :
return x * y
def divide(x, y) :
return x / y
calculateDict = {"+":add, "-":subtract, "*":multiply, "/":divide}
#print calculateDict["+"](1,2)
#print calculateDict.get("+")(1,2)
def calculate(x, y, symbol) :
print calculateDict.get(symbol)(x, y)
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")
3,常用形式
from __future__ import division
def calculate(x, y, symbol) :
calculateDict = {
"+" : x + y ,
"-" : x - y ,
"*" : x * y ,
"/" : x / y
}
print calculateDict.get(symbol)
calculate(1, 2, "+")
calculate(1, 2, "-")
calculate(1, 2, "*")
calculate(1, 2, "/")