用于循环打印旧值和旧值的总和

Ram*_*ona 6 python python-3.x

我在python中使用for循环来显示旧值和新值的总和.以下是我的代码.

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

    sum = sum+val
print(sum)
Run Code Online (Sandbox Code Playgroud)

并显示此循环的输出 48

但我想显示输出

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
Run Code Online (Sandbox Code Playgroud)

请让我知道我需要在代码中更改以显示这样的输出.

Aus*_*tin 9

您可以遍历列表中的元素,在循环中打印所需的内容并更新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
Run Code Online (Sandbox Code Playgroud)