问题描述
我是使用Python 3.7.1的计算机科学入门课程的学生.
I'm an intro computer science student working in Python 3.7.1.
我们正在与"Additorials"合作,您在其中获取一个数字,然后获取该数字加上该数字之前的每个数字的总和.即:对于数字10-- 10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 55
We were working with "Additorials" where you take a number and take get the sum of the number plus every number before it.Ie: for the number 10-- 10+1+2+3+4+5+6+7+8+9 = 55
我必须编写一个程序来执行此操作.但是,我这样做的方式不起作用,但确实可行.
I had to write a program that performed this operation as a function. However, I did it in a way that shouldn't work, but it does.
def bigAdd(n):
for i in range(0,n):
n+=i
return n
例如,如果我输入数字 10 ,它将返回 55
for example, if I input the number 10, it returns 55
但是...为什么?
如果此循环的上限为n
,并且不断地增加i
,它是否应该因为不断提高其极限而永远运行?为什么它返回任何答案,更不用说正确的答案了?
If the upper limit of this loop is n
, and it is constantly being incremented by i
, shouldn't it run forever because it is constantly raising its limit? Why does it return any answer, let alone the correct one?
推荐答案
您要向 n
添加,最初是10
(或您使用的上限).因此,您的结果确实是10 (the initial value) + 0 + 1 + ... + 9 (from the range)
.
You are adding to n
, which initially is 10
(or whichever upper bound you are using). Thus your result is indeed 10 (the initial value) + 0 + 1 + ... + 9 (from the range)
.
话虽如此,我仍然建议使用n
的初始值来不,而建议使用range(1, n+1)
的sum
,因为这是很多更清晰.
Having said that, I'd still recomment not using the initial value of n
and instead getting the sum
of range(1, n+1)
, as that's much clearer.
>>> sum(range(1, n+1))
55
或者如果您想炫耀:
>>> n*(n+1)//2
55
关于第二个问题:不,第一次输入for
循环时,range(0, n)
仅被评估一次,而不是在每次迭代中均被评估.您可以认为代码大致与此等效:
About your second question: No, the range(0, n)
is evaluated only once, when the for
loop is first entered, not in each iteration. You can think of the code as being roughly equivalent to this:
r = range(0, n) # [0, 1, 2, 3, ..., n-2, n-1]
for i in r:
n+=i
尤其是,Python的for ... in ...
循环不是Java,C和其他语言中已知的典型" for (initialization; condition; action)
循环,而是更类似于"for-each"循环,它遍历给定集合的每个元素,生成器或其他类型的可迭代对象.
In particular, Python's for ... in ...
loop is not the "typical" for (initialization; condition; action)
loop known from Java, C, and others, but more akin to a "for-each" loop, iterating over each element of a given collections, generator, or other kind of iterable.
我现在意识到,这实际上是您的 actual 问题...
Which, I now realise, is actually your actual question...
是的,range
不会创建列表,而是一种特殊的可迭代对象,这就是为什么我说大致".
Yes, a range
does not create a list but a special kind of iterable, that's why I said "roughly".
这篇关于增大循环内范围的上限并不能使其永远运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!