不使用sum()打印整数列表的总和

web*_*bbm 1 python list

我有一个下面定义的函数打印列表中的每个整数,它完美地工作.我想要做的是创建第二个函数,该int_list()函数将调用或重用函数以显示已生成的列表的总和.

我不确定这本身是否由代码本身执行 - 我对Python语法很新.

integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45]

def int_list(self):
    for n in integer_list
        index = 0
        index += n
        print index
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 7

在你的代码中,你index=0在每个循环中进行设置,所以它应该在for 循环之前初始化:

def int_list(grades):   #list is passed to the function
    summ = 0 
    for n in grades:
        summ += n
        print summ
Run Code Online (Sandbox Code Playgroud)

输出:

int_list([5, 10, 15, 20, 25, 30, 35, 40, 45])
5
15
30
50
75
105
140
180
225
Run Code Online (Sandbox Code Playgroud)