
web die
714 PointsFor loop sum = 0 i = 0 for i in range(10): sum = sum + i print sum
Can you pls explain me what is happing in this loop

web die
714 Pointssum = 0
i = 0
for i in range(10):
sum = sum + I
print sum
1 Answer

Steven Parker
177,891 PointsI'm guessing you meant to write little "i" instead of capital "I", and forgot to put the parentheses around the argument to "print". So here's a corrected version with comments:
sum = 0 # start with "sum" at 0
i = 0 # and "i" at 0
for i in range(10): # make "i" go from 0 to 9 while doing the rest
sum = sum + i # increase "sum" by the value of "i"
print(sum) # print out what "sum" is at each step
So the loop will repeat 10 times, the first time "sum" and "i" will both be 0 so it will print "0". The next time 0 + 1 will be "1", then 1 + 2 will be "3", and so on.
You should see these 10 outputs while it runs: 0, 1, 3, 6, 10, 15, 21, 28, 36, 45.

web die
714 PointsThanks a million.
Steven Parker
177,891 PointsSteven Parker
177,891 PointsIt's hard to tell what the code is doing without the punctuation and indentation.
Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area.
Or watch this video on code formatting.