Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop to print old value and sum of old value

I am using for loop in python to display old value and sum of new value. Following is my code.

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:

    sum = sum+val
print(sum)

and the output of this loop is showing 48

But i want to show output like

6
6+5 = 11
11+3 = 14
14+8 = 22
22+4 = 26
26+2 = 28
28+5 = 33
33+4 = 37
37+11 = 48

Please let me know what i need to change in my code to display output like this.

like image 487
Ramona Avatar asked Nov 18 '18 08:11

Ramona


1 Answers

You could just iterate through elements in list, printing the required in the loop and updating the total:

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

total = numbers[0]
print(f'{total}')
for val in numbers[1:]:
    print(f'{total} + {val} = {total + val}')
    total += val

# 6
# 6 + 5 = 11
# 11 + 3 = 14                                                 
# 14 + 8 = 22                                                 
# 22 + 4 = 26                                                 
# 26 + 2 = 28                                                
# 28 + 5 = 33                                                 
# 33 + 4 = 37                                                 
# 37 + 11 = 48
like image 85
Austin Avatar answered Sep 25 '22 06:09

Austin