Skip to ContentGo to accessibility page

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.

Checkpoint

Example 5.3

Available appointments

Consider a doctor's office schedule. Each appointment is 30 minutes long. A program to print available appointments can use a nested for loop where the outer loop iterates over the hours, and the inner loop iterates over the minutes. This example prints time in hours and minutes in the range between 8:00am and 10:00am. In this example, the outer loop iterates over the time's hour portion between 8 and 9, and the inner loop iterates over the time's minute portion between 0 and 59.

    hour = 8
    minute = 0
    while hour <= 9:
      while minute <= 59:
        print(hour, ":", minute)
        minute += 30
      hour += 1
      minute = 0

The above code's output is:

    8 : 0
    8 : 30
    9 : 0
    9 : 30

Concepts in Practice

Nested while loop question set

1.
Given the following code, how many times does the print statement execute?
i = 1
while i <= 5:
  j = 1
  while i + j <= 5:
    print(i, j)
    j += 1
  i += 1
  1. 5
  2. 10
  3. 25
2.
What is the output of the following code?
i = 1

while i <= 2:
  j = 1
  while j <= 3:
    print('*', end = '')
    j += 1
  print()
  i += 1
  1. ******
    
  2. ***
    ***
    
  3. **
    **
    **
    
3.
Which program prints the following output?
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
  1. i = 1
    while i <= 4:
      while j <= 4:
        print(i * j, end = ' ')
        j += 1
      print()
      i += 1
    
  2. i = 1
    while i <= 4:
      j = 1
      while j <= 4:
        print(i * j, end = ' ')
        j += 1
      print()
      i += 1
    
  3. i = 1
    while i <= 4:
      j = 1
      while j <= 4:
        print(i * j, end = ' ')
        j += 1
      i += 1
    

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.

Checkpoint

Concepts in Practice

Nested loop practices

4.
Given the following code, how many times does the outer loop execute?
for i in range(3):
  for j in range(4):
    print(i, ' ', j)
  1. 3
  2. 4
  3. 12
5.
Given the following code, how many times does the inner loop execute?
for i in range(3):
  for j in range(4):
    print(i, ' ', j)
  1. 4
  2. 12
  3. 20
6.
Which program prints the following output?
0 1 2 3
0 2 4 6
0 3 6 9
  1. for i in range(4):
      for j in range(4):
        print(i * j, end = ' ')
      print()
    
  2. for i in range(1, 4):
      for j in range(4):
        print(i * j)
    
  3. for i in range(1, 4):
      for j in range(4):
        print(i * j, end = ' ')
      print()
    

Mixed loops

The two for and while loop constructs can also be mixed in a nested loop construct. Ex: Printing even numbers less than a given number in a list. The outer loop can be implemented using a for loop iterating over the provided list, and the inner loop iterates over all even numbers less than a given number from the list using a while loop.

    numbers = [12, 5, 3]
    
    i = 0
    for n in numbers:
      while i < n:
        print (i, end = " ")
        i += 2
      i = 0
      print()

Try It

Printing a triangle of numbers

Write a program that prints the following output:

     1 2 3 4 5 6 7 8 9
     1 2 3 4 5 6 7 8
     1 2 3 4 5 6 7
     1 2 3 4 5 6
     1 2 3 4 5
     1 2 3 4
     1 2 3
     1 2
     1

Finish!

Try It

Printing two triangles

Write a program that prints the following output using nested while and for loops:

    ****
    ***
    **
    *
    ++++
    +++
    ++
    +
Citation/Attribution
Reuse and redistribution of this content in digital or print format:
  • This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's prior written permission.
  • This book uses the Creative Commons Attribution-NonCommercial-ShareAlike License, which means that you can reuse and modify the material only for noncommercial purposes, must attribute OpenStax, and must distribute any derivative works under the same license.
  • Any commercial printing of this textbook, including using a local or custom printer, must be approved by OpenStax, and proper citation provided.
  • OpenStax-copyrighted images, activities, assessments, and similar components of this book are subject to the same licensing – CC-BY-NC-SA. They can be used for noncommercial purposes with attribution. Commercial use requires permission.
  • Permission requests: Anyone who intends to incorporate this content (including text, images, and other components) into large language models, use it in AI offerings, use it commercially (including in print), and/or has questions about another use case is welcome to complete our reuse request form.
Attribution information
  • If you are redistributing all or part of this book in a noncommercial print format, then you must include on every physical page the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

  • If you are redistributing all or part of this book in a noncommercial digital format, then for every page that includes OpenStax content, you must license the derivative work under the same CC-BY-NC-SA license as the original, and include on every digital page view the following attribution:

    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction

Citation information

The information below includes the information needed to generate citations in most major styles (APA, MLA, etc.); you must reformat and organize the information as needed to fit the requirements of the style. Use the information below to generate a citation. We recommend using a citation tool such as this one.

© Apr 23, 2026 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike License. The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo, and Rice University name, and Rice University logo trademarks, or wordmarks are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.