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)
.
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
Or if you want to show off:
>>> n*(n+1)//2
55
About your second question:1 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 roughly2 equivalent to this:
r = range(0, n) # [0, 1, 2, 3, ..., n-2, n-1]
for i in r:
n+=i
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.
1) Which, I now realise, is actually your actual question...
2) Yes, a range
does not create a list but a special kind of iterable, that's why I said "roughly".