1

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: '+'
dda
  • 6,030
  • 2
  • 25
  • 34
  • 1
    you are iterating doing `for i in x` so `i` is not an index but an element of `x`. Later you cannot do `i-1` (this would only work if i is an index of the list x). If you want both the values and indexes, use `for i, elem in enumerate(x):`, so `elem` will be each of the elements in x, and i will be the corresponding index that you can use to get the previous one `i-1` or the next one `i+1` (be careful on the edge cases when there's no previous or no next element though). If you only want indexes you can do the traditional `for i in range(len(x)):` – Sembei Norimaki Dec 07 '22 at 11:50
  • in your case, you could solve your problem easily by joining the elements of the list into a string "1+2-3" and evaluating it using [ast.literal_eval](https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval) however this is discouraged as it's a potential security breach. Read the question I linked for more info. – Sembei Norimaki Dec 07 '22 at 11:56

2 Answers2

1

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.

Hunter
  • 321
  • 2
  • 11
0

using eval()

Code:-

x = ['1','+','2','-','3']
y="".join(x)
print(eval(y))  

Output:-

0

2nd method:- This will work on your cases..!

Code:-

x = ['1','+','2','-','3']
check=0
for i in x:
    if i=="+" or i=="-":
        check+=1
for i in range(len(x)+check-1): #Assuming The sign (+,-) where present has previous and forward numbers 
    if x[i]=="+":
        temp1=int(x[i-1])+int(x[i+1])
        x.insert(i+2,str(temp1))
    if x[i]=="-":
        temp2=int(x[i-1])-int(x[i+1])
        x.insert(i+2,str(temp2))
#print(x)   #values how store in the list
print(x[-1])

Output:-

0
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20