简体   繁体   中英

Total of mathematical expression in python

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??

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM