计算数学表达式 (python)

Evaluating a mathematical expression (python)

print('Enter a mathematical expression: ')  
expression = input()  
space = expression.find(' ')  
oprand1 = expression[0 : space]  
oprand1 = int(oprand1)  
op = expression.find('+' or '*' or '-' or '/')  
oprand2 = expression[op + 1 : ]  
oprand2 = int(oprand2)  
if op == '+':  
 ans = int(oprand1) + int(oprand2)  
 print(ans)  

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

我会按照这些思路提出一些建议,我认为你 从输入表达式中解析值可能过于复杂。

您可以简单地在输入字符串上调用 .split() 方法,默认情况下 在 space ' ' 上拆分,因此字符串 '1 + 5' 将 return ['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))