如何存储和使用数学运算符作为python变量

How to store and use mathematical operators as python variable

我对python不太熟悉,尝试在下面编写类似的代码(代码A),因此它与代码B非常相似。我想使用用户输入的数学运算符作为do_what变量。我们如何用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感兴趣。这会将ifelse循环减少为针对您的这个特定示例的单个语句

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

编辑

在这种情况下,为了使eval稍微安全一些,您可以使用类似的东西

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代码编写的所有内容,因此如果您打算让其他人使用它,请不要这样做。