Intro to Computer Science / Unit 6: Loops
6.4 Nested Loops
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=""stopsprintfrom starting a new line, andprint()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?4 x 5 = 20.
What does the nested loop above print if the outer range is
range(3) and the inner range is range(2)?There are 3 outer repeats, each printing 2 stars on a line.
In a nested loop, when does the inner loop restart?
The inner loop finishes all its repetitions for each single outer repetition.
Ready for more? Take the Unit 6 test.