Stephen Stephen - 1 month ago 9
Python Question

Python:How to make the sum of the values of a while loop store into a variable?

I'm just a beginner :P.
I'm doing a tutorial about while loops on Codeacademy "Click here!" ,
but I've gotten stuck on this part: Write a while loop which stores into "

theSum
" the sum of the first 10 positive integers (including 10).This is what it gives you to work with:

theSum = 0
num = 1
while num <= 10:
print num
num = num + 1


It prints out the numbers 1 to 10 on seperate lines in the console. Can anyone explain to me how I can get it to store the sum of the values in the variable "
mySum
"? Anything I've tried so far hasn't worked for me. :(

EDIT:
Okay so I just tried this:

theSum = 0
num = 1
while num <= 10:
num += 1
mySum = num
mySum = mySum + num

print mySum


This gives me 22, why is that? Am I in anyway close? (Thanks for all the replies but I'll try again tomorrow.)

EDIT: Okay, I got it! Thank you for the help. :)

mySum = 0
num = 1
while num <= 10:
mySum += num
num += 1
print mySum

Answer

The code you have already shows almost everything needed.

The remaining problem is that while you are correctly generating the values to be added (num) inside your while-loop, you are not accumulating these values in your variable theSum.

I won't give you the missing code on purpose, so that you can learn something from your question ... but you need to add the value of num to your variable theSum inside the loop. The code for doing this (it's really only one statement, i.e., one line of code) will be somewhat similar to how you are dealing with/updating the value of num inside your loop.

Does that help?