How to store and use mathematical operators as python variable
我对python不太熟悉,尝试在下面编写类似的代码(代码A),因此它与代码B非常相似。我想使用用户输入的数学运算符作为
代码A
1 2 3 4 5 | num1 = input("Enter a number:") num2 = input("Enter another number:") do_what = input("Enter a calculation symbol for calculation you want to perform:") result = float(num1) do_what float(num2) print("result is:" + str(result)) |
代码B
1 2 3 4 | num1 = input("Enter a number:") num2 = input("Enter another number:") result = int(num1) + int(num2) print("result is:" + str(result)) |
您可以将运算符模块用于常用运算符,并创建查找字典以将符号映射到函数。如果您不希望操作员出现在该模块中,您可以简单地定义自定义函数,并以相同的方式添加查找它们:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import operator operatorlookup = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv } num1 = input("Enter a number:") num2 = input("Enter another number:") do_what = input("Enter calculation symbols for calculation you want to perform:") op = operatorlookup.get(do_what) if op is not None: result = op(float(num1), float(num2)) else: result ="Unknown operator" print("result is:" + str(result)) |
您可能还对了解内置函数eval感兴趣。这会将
1 2 3 4 5 6 7 8 9 10 11 | num1 = input("Enter a number:") num2 = input("Enter another number:") do_what = input("Enter calculation symbols for calculation you want to perform:") result = eval(num1 + do_what + num2) print("result is: %s" %result) # Enter a number: 3 # Enter another number: 18 # Enter calculation symbols for calculation you want to perform: * # result is: 54 |
编辑
在这种情况下,为了使
1 2 3 4 5 | if do_what in ['+', '-', '*', '**', '/']: result = eval(num1 + do_what + num2) print("result is: %s" %result) else: print ("Enter an arithmetic operator") |
1 2 3 4 5 6 7 8 9 10 11 12 | num1 = input("Enter a number:") num2 = input("Enter another number:") do_what = input("Enter calculation symbols for calculation you want to perform:") if do_what=='+': result = float(num1) + float(num2) elif do_what=='-': result = float(num1) - float(num2) elif do_what=='*': result = float(num1) * float(num2) elif do_what=='/': result = float(num1) / float(num2) print("result is:" + str(result)) |
如果您不关心安全问题,您可以使用eval来实现这一点。
1 | result = eval(str(num1) + do_what + str(num2)) |
问题是,eval从字面上评估了您作为python代码编写的所有内容,因此如果您打算让其他人使用它,请不要这样做。