Use two numbers from a list to do simple calculations in Python

109 Views Asked by At

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: '+'
2

There are 2 best solutions below

1
Hunter On BEST ANSWER

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.

0
Yash Mehta On

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