- from __future__ import division
- # if used this, 5/2=2.5, 6/2=3.0
- def add(x, y):
- return x + y
- def sub(x, y):
- return x - y
- def mul(x, y):
- return x * y
- def div(x, y):
- return x / y
- operator = {"+": add, "-": sub, "*": mul, "/": div}
- operator["+"](1, 2) # the same as add(1, 2)
- operator["%"](1, 2) # error, not have key "%", but the below will not
- operator.get("+")(1, 2) # the same as add(1, 2)
- def cal(x, o, y):
- print operator.get(o)(x, y)
- cal(2, "+", 3)
- # this method will effect than if-else
Python基础之——使用字典和函数构造switch
最新推荐文章于 2021-11-24 10:34:08 发布