Question

Write a while loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result:

21 which is 1 + 2 + 3 + 4 + 5 + 6.

Is anybody able to guide me through this, without spoiling it for me?

Was it helpful?

Solution

There are two things you can do. The "fast" way (a la the story about the young Gauss) recognizes that

sum(1:N) = N * (N + 1) / 2

But I doubt that is what is asked.

You need to create a loop (look at the for command) over a range (look at the range command), and in each iteration add the current value of the loop variable to the sum (which you initialize to zero before the start of the loop).

There - you should now be OK.

EDIT with a while loop, and still leaving you to do a little bit of work:

mySum = 0
i = 1;
while( <<< put some condition here >>> ):
  mySum = mySum + i
  <<<<< do something clever with i >>>>>
print <<<<< what do you think you should print here? >>>>>

Note that indentation is important in Python, and the : at the end of the while statement matters

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top