如何在运算中使用算术运算符(由用户作为字符串输入)?我可以打印操作本身,但我想打印解决方案!
这是我的笨拙尝试:
# 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)
Use the operator module http://docs.python.org/2/library/operator.html,它具有执行与算术运算相同的操作的函数。
import operator
ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}
op = input("Please enter *, /, +, or - : ")
result = ops[op](x, y)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)