a question about "for loop" and "range" function. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

a question about "for loop" and "range" function.

#for this code,why the output is 10 rather than 20? x=0 for i in range(5): for j in range(i): x+=j print(x) """ I thought the output should be 0+(0+1)+(0+1+2)+(0+1+2+3)+(1+2+3+4)=20, but the real output is 10,why?I get confused. """

27th May 2017, 11:41 PM
Bluebear
Bluebear - avatar
3 Answers
+ 8
Iterations: 1. 0to0 = no increase 2. 0to1 = +0 3. 0to2 = +0+1 4. 0to3 = +0+1+2 5. 0to4 = +0+1+2+3 Sum: 10
27th May 2017, 11:58 PM
Tim G
Tim G - avatar
+ 5
@James Long explainations can be really good, you are right there. I always try to explain it long too. But this one was a bit tricky, even for me. Sometimes you have to keep things simple🛀
28th May 2017, 12:23 AM
Tim G
Tim G - avatar
+ 3
trying to replicate the code: i = 0 --> x = 0 i = 1 --> x = 0 + 0 = 0 i = 2 --> x = 0 + 0 + 1 = 1 i = 3 --> x = 1 + 0 + 1 + 2 = 4 i = 4 --> x = 4 + 0 + 1 + 2 + 3 = 10
28th May 2017, 12:10 AM
Ulisses Cruz
Ulisses Cruz - avatar