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

时间:2019-02-06 17:32:05

标签: python

我是python的新手,正尝试在下面(代码A)编写类似的内容,因此它的确与代码B相似。我想将数学运算符的用户输入用作do_what变量。我们如何用Python编写此代码(A),使其像代码B一样工作?

代码A

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

num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = int(num1) + int(num2)
print("result is: " + str(result))

4 个答案:

答案 0 :(得分:5)

您可以将operator module用于常见的运算符,并创建一个查找字典以将符号映射到函数。如果您希望运算符不在该模块中,则只需定义自定义函数并以相同的方式查找它们:

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))

答案 1 :(得分:4)

您可能还想了解内置函数eval。这样可以将resource "azurerm_recovery_services_protection_policy_vm" "test"{ name = "DefaultPolicy" resource_group_name = "${var.recovery_vault_resource_group_name}" recovery_vault_name = "${var.recovery_vault_name}" backup = { frequency = "Daily" time = "09:30" } retention_daily = { count = 10 } } if循环简化为您的特定示例的单个语句

else

编辑

在这种特殊情况下,为了使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

答案 2 :(得分:2)

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))

答案 3 :(得分:0)

如果您不关心安全性,可以使用eval来实现这一目标

result = eval(str(num1) + do_what + str(num2))

问题是eval从字面上评估了您以python代码编写的所有内容,因此如果您要让其他人使用它,请不要这样做