评估数学表达式(python)

时间:2016-11-06 21:48:00

标签: python string int find mathematical-expressions

{{1}}

因此,假设用户输入2 + 3,每个字符之间有一个空格。如何打印2 + 3 = 5?我需要代码来处理所有操作。

1 个答案:

答案 0 :(得分:0)

我会根据这些思路提出建议,我想你 可能有过于复杂的解析输入表达式中的值。

您可以在输入字符串上调用.split()方法,默认情况下 在空间上分裂' ',所以字符串' 1 + 5'会返回[' 1',' +',' 5']。 然后,您可以将这些值解压缩到三个变量中。

print('Enter a mathematical expression: ')  
expression = input()  
operand1, operator, operand2 = expression.split()
operand1 = int(operand1)
operand2 = int(operand2)  
if operator == '+':  
 ans = operand1 + operand2  
 print(ans)
elif operator == '-':
    ...
elif operator == '/':
    ...
elif operator == '*':
    ...
else:
    ...  # deal with invalid input

print("%s %s %s = %s" % (operand1, operator, operand2, ans))