Python Arena
Step 4 of 4

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")
Output
onetwo three
four

One 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
Output
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

row 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
Output
1 2 3

The 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
Output
1
1 2
1 2 3
1 2 3 4

Row 1 has one number, row 2 two numbers, and so on, because the inner loop runs while column <= row.

Your task

Challenge 1 of 3

This program should print a rectangle of # characters, but it prints only the first row. Fix it.

Height: 3
Width: 5
#####
#####
#####

Challenge 2

Write a program that asks for a size and prints a hollow square: # characters on the edges and spaces inside.

Size: 4
####
#  #
#  #
####

Challenge 3

Write a program that asks for a number of rows and prints a triangle of numbers that keep counting up from one row to the next: row 1 has one number, row 2 has two, and so on.

Rows: 4
1
2 3
4 5 6
7 8 9 10