The easiest way to understand how this works is to build up to it, a line at a time. Start with the outside loop, and add an extra print so we can see what is happening:
for i in range(6):
print("i =", i)
It really will help for you to actually run the code and watch what it does. We’re going to experiment and build up to the final version.
Run the first version with just two lines, and see what it does. Does it make sense to you?
Hints:
- What is the starting value for i?
- What is the last value that i gets?
- Is the 6 included or excluded in the values for i?
Once you understand what its doing, let’s add the inner loop, with a print to see what it does:
for i in range(6):
print("i =", i, "i+1 =", i+1)
for j in range(1, i+1):
print("j =", j)
Run that, and see if you can work out what is happening. Hints:
- When i = 5, what numbers does the inner loop (j) count?
- When i = 4, what numbers does the inner loop count?
- Can you see a pattern?
- What about the very first loop, when i=0, what does the inner loop do?
Notice that print
always puts its output on a new line. Let’s change the inner loop print:
for i in range(6):
print("i =", i, "i+1 =", i+1)
for j in range(1, i+1):
print(j, end=" ")
Instead of ending each print with a new line, each print ends with a space, and the next loop stays on the same line. Is that clear?
You will notice that, except for the first line “i = 0 i+1 = 1” each of
the “i” printed lines are on the same line as the j lines. That’s
because after printing the j values we still haven’t started a new line.
Let’s fix that:
for i in range(6):
print("i =", i, "i+1 =", i+1)
for j in range(1, i+1):
print(j, end=" ")
# reduce the indentation to match the i loop again.
print("after the j loop")
Is that still clear?
Now let’s get rid of the “after the j loop” message and replace it by just a single space. (The space will be invisible, so you can’t see it, but it will still give us a new line at the end.)
for i in range(6):
print("i =", i, "i+1 =", i+1)
for j in range(1, i+1):
print(j, end=" ")
# reduce the indentation to match the i loop again.
print(" ")
And now finally let’s get rid of the print that shows the i values, as we don’t need it.
for i in range(6):
for j in range(1, i+1):
print(j, end=" ")
# reduce the indentation to match the i loop again.
print(" ")
And now, hopefully, you have worked out for yourself what each line does.
If not, and you still have questions, please ask!