不使用sum()打印整数列表的和 [英] Print the sum of a list of integers without using sum()

查看:102
本文介绍了不使用sum()打印整数列表的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面定义了一个函数,该函数可以打印列表中的每个整数,并且效果很好.我想做的是创建第二个函数,该函数将调用或重新利用int_list()函数来显示已生成列表的总和.

I have a function defined below that prints each integer in the list, and it works perfectly. What I would like to do is create a second function that would call on or reutilize the int_list() function to display a sum of the list that's been generated.

我不确定这是否是代码本身固有的功能-我对Python语法还是很陌生.

I am not sure if that has been inherently performed by the code itself - I am rather new to the Python syntax.

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

推荐答案

在您的代码中,您需要在每个循环中设置index=0,因此应在for循环之前对其进行初始化:

In your code, you're setting index=0 in every loop, so it should be initialized before the for loop:

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

输出:

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

这篇关于不使用sum()打印整数列表的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆