Sign in

Intro to Computer Science / Unit 6: Loops

6.4 Nested Loops

3 practice questionsNot yet reviewed

Notes

A nested loop is a loop inside another loop. The inner loop runs completely for each repetition of the outer loop.

for row in range(2):
for col in range(3):
print("*", end="")
print()
  • Output: *** on one line, then *** on a second line.
  • end="" stops print from starting a new line, and print() alone moves to the next line.
  • Total repetitions of the inner body = outer count x inner count. Here 2 x 3 = 6 stars.
  • Nested loops are used for grids, tables and comparing every pair of items.

Practice

A nested loop has an outer for that runs 4 times and an inner for that runs 5 times. How many times does the inner body run in total?
What does the nested loop above print if the outer range is range(3) and the inner range is range(2)?
In a nested loop, when does the inner loop restart?

Ready for more? Take the Unit 6 test.