← All lessons

Nested loops

Sign in · Sign up

Lesson 3.6

A loop can sit inside another loop. The outer one is in charge of rows, the inner one of columns:

for row in range(3):
    for col in range(3):
        print("*", end=" ")
    print()

There are three new things here:

  • end=" " in print — after the star, don't move to a new line but put a space;
  • indentation: the body of the inner loop is shifted 4 more spaces;
  • print() after the inner loop — a line break for the next row of the square.

Draw a rectangle of stars: rows rows, each with cols stars separated by spaces. rows and cols are set by the check.

Hint

rows lines, cols stars in a line: two nested loops.

The inner loop prints stars with end=" ", so they stay on one line. After the inner loop you need an empty print() — a line break.