Stack Exchange
Calculator not giving correct result
I need to create something like a calculator using Python.
So far, I have tried the code below but it does not work as expected.
symbol = 0
a = []
b = []
while symbol != '=':
    num = int(input("Number:"))
    a.append(num)
    symbol = (input("Symbol:"))
    if symbol in('+','-','*','/','='):
        b.append(symbol)
b.remove(b[-1])
print(a,b)

for i in a,b:
    if b[i] == '+':
        a[i] = a[i] + a[i + 1]
    elif b[i] == '-':
        a[i] = a[i - 1] - a[i - 1]
    elif b[i] == '*':
        a[i] = a[i - 1] * a[i - 1]
    elif b[i] == '/':
        a[i] = a[i - 1] / a[i - 1]
    print(a[i])


You are not using the for loop correctly. Let's say that a = [1, 2, 3] and b = ['+', '-'], therefore, for i in a, b the variablei will assume the value of a in first iteration and then the value of b in the second iteration.
If you want to iterate through the list by the indexes, do the following:
# `i` goes in the range [0, len(b)), not include b
for i in range (len(b)):
     ...

Considering that there is no precedence for operators and that the evaluation of the expression is from left to right, we can arrive at the following code:
symbol = 0
a = []
b = []
while symbol != '=':
    num = int(input("Number:"))
    a.append(num)
    symbol = (input("Symbol:"))
    if symbol in('+','-','*','/','='):
        b.append(symbol)

b.remove(b[-1])
print(a,b)

for i in range(len(b)):
    print('Op: {} {} {}'.format(a[i], b[i], a[i+1]), end='')
    if b[i] == '+':
        a[i+1] = a[i] + a[i + 1]
    elif b[i] == '-':
        a[i+1] = a[i] - a[i+1]
    elif b[i] == '*':
        a[i+1] = a[i] * a[i+1]
    elif b[i] == '/':
        a[i+1] = a[i] / a[i+1]
    print(' = {}'.format(a[i+1]))

# Answer is the last value of "a" list
print(a[-1])

