Login
📚 Introduction to Python Programming
Chapters ▾
⇩ Download ▾

5.3 Nested loops

Learning objectives

By the end of this section you should be able to

  • Implement nested while loops.
  • Implement nested for loops.

Nested loops

A nested loop has one or more loops within the body of another loop. The two loops are referred to as outer loop and inner loop. The outer loop controls the number of the inner loop's full execution. More than one inner loop can exist in a nested loop.

Nested for loops

A nested for loop can be implemented and used in the same way as a nested while loop. A for loop is a preferable option in cases where a loop is used for counting purposes using a range function, or when iterating over a container object, including nested situations. Ex: ​​Iterating over multiple course rosters. The outer loop iterates over different courses, and the inner loop iterates over the names in each course roster.