Search code examples
pythonstringintfindmathematical-expressions

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)  

So lets say the user enters 2 + 3 with a space in between each character. How would I get it to print 2 + 3 = 5? I need the code to work with all operations.


Solution

  • I would suggest something along these lines, I think that you may have over complicated parsing the values out of the input expression.

    You can simply call the .split() method on the input string, which by default splits on a space ' ', so the string '1 + 5' would return ['1', '+', '5']. You can then unpack those values into your three variables.

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