3 回答

TA贡献1829条经验 获得超6个赞
您可以使用operator模块和dict!
import operator
op = {
"+": operator.add
"-": operator.sub
"/": operator.truediv
"//": operator.floordiv
"*": operator.mul
"**": operator.pow
"%": operator.mod
}
print(op["+"](2, 3))
5

TA贡献1783条经验 获得超4个赞
它与@Fukiyel的答案基本相同,但没有使用operator模块。您实现了您希望计算器支持的所有操作,然后您创建了一个 dict,其中包含操作符字符的键并对函数进行赋值:
def add(n1,n2):
return n1 + n2
def subtract(n1,n2):
return n1 - n2
def division(n1,n2):
if n2 != 0:
return n1 / n2
def integerDivision(n1,n2):
if n2 != 0:
return n1 // n2
def multiply(n1,n2):
return n1 * n2
def power(n1,n2):
return n1 ** n2
def modulo(n1,n2):
return n1 % n2
__operators = {'+' : add, '-' : subtract, '/' : division, '//' : integerDivision, '*' : multiply, '**' : power, '%' : modulo}
def calculator():
x = int(input())
operator = input()
y = int(input())
for op in __operators:
if operator == op:
result = __operators[operator](x,y)
print(result)
return result
calculator()
添加回答
举报