[Python] why am I getting different results?


#1



Hi everybody:

This is the first message I've ever posted here. I'm new to Python.
I was stuck at the "Iterating over a list in a function" exercise, and after a long while trying to solve it, I finally got the right answerr. The thing is I got two different results, as you can see below. why is it that I kept getting two different results?
What seems to make the difference is the fact that the variable total be after or before the for loop.

Thank you very much, I'm sorry if it's not the right place to post it.

 def papa(a):
	total = 0
	for i in range(len(a)):
		total = total + a[i]
	return total

n = [0,3,6]
papa(n)
6


def papa(a):
	for i in range(len(a)):
		total = 0
		total = total + a[i]
	return total

n = [0,3,6]
papa(n)
9


#2

In your first code you have assign total=0 before for loop. So it will change with every iteration.
initially total =0
Before 1st iteration total=0 , After 1st iteration total=0
Before 2nd iteration total=0 , After 2nd iteration total=3
Before 3rd iteration total=3 , After 3rd iteration total=9

But in second code you have assign total=0 in for loop. So it will become zero before every iteration.
Before 1st iteration total=0 , After 1st iteration total=0
Before 2nd iteration total=0 , After 2nd iteration total=3
Before 3rd iteration total=0 , After 3rd iteration total=6