1

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
>>>
jamylak
135k30 gold badges238 silver badges240 bronze badges
asked Apr 24, 2012 at 7:53
3
  • 0+1+2+3+4, and parts of that... Commented Apr 24, 2012 at 7:57
  • Could you explain a little more please? How the range works? and why it outputs those integers? I know its simple code, just need a little help. Commented Apr 24, 2012 at 8:01
  • Programming questions are off-topic for Super User. We have a site dedicated for programming called Stack Overflow, but you probably shouldn't post these simple "Here's some code, what does it do?" questions. You need to show us what you already found out, do a little research, et cetera. Commented Apr 24, 2012 at 8:03

1 Answer 1

2

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
jamylak
135k30 gold badges238 silver badges240 bronze badges
answered Apr 24, 2012 at 8:01
Sign up to request clarification or add additional context in comments.

1 Comment

Ok I understand the range now. Thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.