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

69,008

Solution 1

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?

Solution 2

Lets take a dry run through the code you've posted. I've numbered the lines so I can refer to them.

1. num = 1
2. while num <= 10:
3.     num += 1
4.     mySum = num
5.     mySum = mySum + num

6. print mySum

Here's a dry run

1. simple enough, create a new variable `num` and bind it to the number `1`
2. `num` is less than 10, so do the body of the loop
3. `num` is `1` so now bind it to `2`
4. create a new variable `mySum` and bind to `2` (same as num)
5. `mySum` is `2` and `num` is `2` so bind `mySum` to `4`
Back to the top of the loop
2. `num` is less than 10, so do the body of the loop
3. `num` is `2` so now bind it to `3`
4. bind `mySum` to `3` (same as num)
5. `mySum` is `3` and `num` is `3` so bind `mySum` to `6`
Back to the top of the loop
2. `num` is less than 10, so do the body of the loop
3. `num` is `3` so now bind it to `4`
4. bind `mySum` to `4` (same as num)
5. `mySum` is `4` and `num` is `4` so bind `mySum` to `8`
Back to the top of the loop
...

looks like something is not going right. Why are you doing this mySum = num inside the loop? What do you expect it to do?

Share:
69,008
Admin
Author by

Admin

Updated on March 12, 2020

Comments

  • Admin
    Admin about 4 years

    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