如何在操作中使用算术运算符(用户输入为字符串)?我可以打印操作本身,但我想打印解决方案!
这是我笨拙的尝试:
# Initialise variables
x = 2
y = 3
# Prompt the user for an arithmetic operator
operator = input("Please enter *, /, +, or - : ")
# Calculate the operation
result = (str(x) + operator + str(y))
# Display the result
print(result)
答案 0 :(得分:4)
使用operator
module,其函数执行与算术运算相同的操作。
import operator
ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}
op = input("Please enter *, /, +, or - : ")
result = ops[op](x, y)