Reputation: 13
[Background info: I am currently completing a course on Python programming from the MIT edx site, and am working on the section on while loops.]
The question I have been struggling with is as follows: "Write a while loop that sums the values 1 through end, inclusive. end is a variable that we define for you."
When I tried answering the question, I put:
while end != 0:
total = 0 + end
end = end-1
print total
The return result for any value I put in for 'end' was 1, which obviously is incorrect.
However, when I tried again, I defined 'total' outside of the loop, and put:
total = 0
while end != 0:
total = total + end
end = end-1
print total
This works!
My question is: why does the first code that I put in not work? What is the significance of defining 'total' outside of the loop?
Upvotes: 1
Views: 2704
Reputation: 50540
In your first code block, each time you run total = 0 + end
, you reset total
total = 0 + 10
total = 0 + 9
total = 0 + 8
...
total = 0 + 1
At the end of this, the last line run was total = 0 + 1
which equals 1
In the second loop, you are utilizing the previous value of total
:
total = 0
total = 0 + 10
total = 10 + 9
total = 19 + 8
...
total = 54 + 1
With each pass through the loop, total is incremented and utilized. In the first one, you are over writing the total in each loop.
Upvotes: 1
Reputation: 188
In the example with total
inside the while loop, it is being redefined each time end != 0
, and you are printing it right after end
was equal to 1 (end = end-1
will make break you out of the while loop after end is equal to 1).
In the other example, you are not redefining total
each trip through the while loop, and this is accumulating the answer you expect.
Upvotes: 0
Reputation: 49320
The problem lies with total = 0 + end
. What this does is assign the current value of end
to total
. Since end
eventually becomes 1
, that's what total is. You need to add end
to the running total
:
total = total + end
or:
while end != 0:
total += end
end -= 1
print total
Upvotes: 1
Reputation: 448
When you define total
inside the while loop, it reassigns itself to 0 + end
each time it loops, which is 1 by the end of the program. When you define it outside, it sets total
to 0, then for each loop within while
, it continues to add the value to it.
Also, sidenote, you can write total = total + end
as total += end
and it means the same thing but is actually a (very) small bit faster.
Upvotes: 0