Mike X
Mike X

Reputation:

Python 2.5 for loop

I am having a little trouble understanding this simple for loop code. I just need help explaining why it outputs the way it does.

y=0
for x in range(5):
    y=y+x
    print y

>>>
0
1
3
6
10
>>>

Upvotes: 1

Views: 634

Answers (1)

rskuja
rskuja

Reputation: 571

range(5) gives you

[0,1,2,3,4]

in for loop you add up

y(0) = y(0) + x(0) >>> 0
y(1) = y(0) + x(1) >>> 1
y(3) = y(1) + x(2) >>> 3
y(6) = y(3) + x(3) >>> 6
y(10) = y(6) + x(4) >>> 10

Upvotes: 2

Related Questions