For loop to print old value and sum of old value

  • A+
Category:Languages

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.

 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: