Helper variables in nested loops
Nested loops often print a pattern, a little piece at a time. For that, print has an option you met in part 1: print(..., end=""). Normally print ends its line, so the next print starts a new one. With end="", it ends with nothing instead, and the next print carries on where this one stopped. Any other text works as the ending too, such as a space. A print() with nothing in it then just ends the line:
print("one", end="")
print("two", end=" ")
print("three")
print("four")
onetwo three
fourOne helper variable per loop
In nested loops, each loop needs a helper variable of its own, and the inner one must start again in every round of the outer loop. This program prints a multiplication square:
size = 4
row = 1
while row <= size:
column = 1
while column <= size:
print(row * column, end=" ")
column += 1
print()
row += 1
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16row counts the rows, and column counts the numbers on one row. column = 1 is inside the outer loop, just before the inner loop, so every row starts again from column 1. After the inner loop, print() ends the row.
The start value in the wrong place
This is the most common mistake with nested loops: the inner helper variable gets its start value only once, before the outer loop.
row = 1
column = 1
while row <= 3:
while column <= 3:
print(row * column, end=" ")
column += 1
print()
row += 1
1 2 3The first row is fine. But after it, column is 4, and nothing sets it back to 1. In every later round of the outer loop, column <= 3 is false from the start, so the inner loop doesn't run, and the other rows are empty.
Rows of different lengths
The inner loop's condition can use the outer loop's variable. Then each row can have a length of its own:
height = 4
row = 1
while row <= height:
column = 1
while column <= row:
print(column, end=" ")
column += 1
print()
row += 1
1
1 2
1 2 3
1 2 3 4Row 1 has one number, row 2 two numbers, and so on, because the inner loop runs while column <= row.