- 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 发布
本文介绍了一种使用Python将基本算术操作如加、减、乘、除封装成函数的方法,并通过字典来实现算术操作的选择。这种方式避免了使用冗长的if-else语句,使代码更简洁易读。
877

被折叠的 条评论
为什么被折叠?



