Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - Print the sum of a list of integers without using sum()

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.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...