I just started my journey into programming with Python and after I finished traversy's crash course video I started doing some small programs to get better at it, but I ran into a problem.
Let's say you ask the user to input a simple math computation, it looks like this and you want to do the addition in this case:
x = ['1','+','2','-','3']
Then I wanted to do a for loop that scans for the + and adds the number before and after the +
symbol. But when it prints the supposed result it just prints the entire list.
for i in x:
if i == "+":
add_sum = float(calc_List[i-1]) + float(calc_List[i+1])
print(add_sum)
And I get this message in the terminal when I run it:
add_sum = float(x[i-1]) + float(x[i+1])
~^~
TypeError: unsupported operand type(s) for -: 'str' and 'int'
It seems I can't write it like this, but how can I choose the previous and next number from i
in a list and then do any kind of calculation?
I tried to keep the i
count into a separate variable like this:
position = 0
for i in x:
position += 1
if i == '+':
a = position - 1
b = position + 1
add_sum = float(x[a]) + float(x[b])
But all I got was this error:
add_sum = float(x[a]) + float(x[b])
^^^^^^^^^^^
ValueError: could not convert string to float: '+'
You need to find the index of i
within x
and then find the before and after value in the list. This can be achieved like this:
x = ['1', '+', '2', '-', '3']
for i in x:
if i == "+":
add_sum = float(x[x.index(i)-1]) + float(x[x.index(i)+1])
print(add_sum)
This outputs:
3.0
Hope this helps.