-3

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?

4

1 回答 1

2

你可以做两件事。“快速”的方式(关于年轻的高斯的故事)认识到

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

但我怀疑这就是所要求的。

您需要for在一个范围内(查看命令)创建一个循环(查看range命令),并在每次迭代中将循环变量的当前值添加到总和(在循环开始之前将其初始化为零) .

那里 - 你现在应该没事了。

用while循环编辑,仍然让你做一些工作:

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? >>>>>

请注意,缩进在 Python 中很重要,语句:末尾的while

于 2013-10-29T23:09:33.360 回答