Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (2015) Letter Game App Letter Game Refinement

For 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

Steven Parker
Steven Parker
231,268 Points

It'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. :arrow_heading_down:   Or watch this video on code formatting.

sum = 0
i = 0
for i in range(10):
  sum = sum + I
  print sum

1 Answer

Steven Parker
Steven Parker
231,268 Points

I'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.

Thanks a million.