0
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.

1 Answers1

0

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))
chatton
  • 596
  • 1
  • 3
  • 8
  • Can you explain to me what the 3 dots mean and what "%s %s %s = %s" mean? – computer science noob Nov 06 '16 at 22:06
  • of course! I just did the ... to indicate you can just fill out those sections like the previous one. It's not actual code. – chatton Nov 06 '16 at 22:08
  • The %s is a format string, you can provide values (in this case the operators and the operand and the answer). each %s corresponds with the value you pass in after the %. I found them quite confusing at first. There's a string.format method which I think is actually better practice. So you can read up on that too – chatton Nov 06 '16 at 22:09
  • In terms of string formatting, the last line would look like `print("{} {} {} = {}".format(operand1, operator, operand2, ans))` – idjaw Nov 06 '16 at 22:12