Nested while loops let you repeat actions inside other repeated actions. This helps when you want to work with groups inside groups, like rows and columns.
0
0
Nested while loops in Python
Introduction
When you want to print a grid or table of values.
When you need to check every item inside a list of lists.
When you want to repeat a process inside another repeated process, like a game board.
When you want to create patterns with characters or numbers.
When you need to handle multiple levels of choices or steps.
Syntax
Python
while condition1: # outer loop code while condition2: # inner loop code
The inner loop runs completely for each time the outer loop runs once.
Indentation is important to show which loop the code belongs to.
Examples
This prints pairs of i and j values, showing how the inner loop runs fully for each i.
Python
i = 1 while i <= 3: j = 1 while j <= 2: print(f"i={i}, j={j}") j += 1 i += 1
This multiplies numbers from two loops and prints the results.
Python
count = 1 while count <= 2: inner = 1 while inner <= 3: print(count * inner) inner += 1 count += 1
Sample Program
This program prints coordinates in a 3 by 4 grid. The outer loop controls rows, and the inner loop controls columns.
Python
row = 1 while row <= 3: col = 1 while col <= 4: print(f"({row},{col})", end=' ') col += 1 print() # move to next line row += 1
OutputSuccess
Important Notes
Make sure the inner loop resets its variable each time the outer loop runs.
Be careful to change loop variables inside loops to avoid infinite loops.
Use print() without arguments to move to the next line after inner loop finishes.
Summary
Nested while loops let you repeat actions inside other repeated actions.
The inner loop runs fully for each time the outer loop runs once.
They are useful for working with grids, tables, or multi-level data.