Home > Blockchain >  Total of mathematical expression in python
Total of mathematical expression in python

Time:02-20

I written a part of a my code to calculate the total of mathematical expression.(This not a full code it is a part of my code)

tot=10
temp=''
b=[' 20', '-5', '*4', '/50']
for i in range(0,len(b)):
  temp=str(tot) b[i]
  tot =int(eval(temp))
print(tot)

In above code i am printing the total of expression

explanation:

10 20 ->30
30-5 -> 25
25*4 -> 100
100/50 -> 2 

Output i got:

 382

Output i need:

2

Is my code is incorrect what changes i need to do??

CodePudding user response:

You are adding the evaluation in every iteration to total so the output you get is the sum of all answers. Rather, change the value of tot in every iteration.
Code:

tot=10
temp=''
b=[' 20', '-5', '*4', '/50']
for i in range(0,len(b)):
  temp=str(tot) b[i]
  tot=int(eval(temp))
print(tot)

CodePudding user response:

Just for fun (and assuming you have Python 3.10) you can avoid eval() (which is generally frowned upon anyway) with this:

total = 10
b = [' 20', '-5', '*4', '/50']

for e in b:
    v = int(e[1:])
    match e[0]:
        case ' ':
            total  = v
        case '-':
            total -= v
        case '*':
            total *= v
        case '/':
            total /= v
        case _:
            pass
print(total)

Output:

2.0

This also avoids the string manipulation seen in your original question and in some answers

  • Related