Nested Loop
Part of the Fundamentals section of Coddy's Python journey — lesson 41 of 77.
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
Let's start with a simple nested loop to understand the concept:
# Outer loop
for i in range(3):
print(f"Outer loop iteration: {i}")
# Inner loop
for j in range(2):
print(f" Inner loop iteration: {j}")When you run this code, you'll see:
Outer loop iteration: 0
Inner loop iteration: 0
Inner loop iteration: 1
Outer loop iteration: 1
Inner loop iteration: 0
Inner loop iteration: 1
Outer loop iteration: 2
Inner loop iteration: 0
Inner loop iteration: 1Notice that for each iteration of the outer loop, the inner loop completes all of its iterations.
Now let's see a practical example - printing a simple pattern:
# Print a 2x3 rectangle of stars
for row in range(2): # 2 rows
line = ""
for col in range(3): # 3 columns
line += "*"
print(line)
# Output:
# ***
# ***The outer loop controls how many rows we print, and the inner loop builds each row by adding stars.
Challenge
EasyWrite code that prints a rectangle pattern of stars (*) using nested loops.
Your program should:
- Read two integers:
rowsandcols - Use a nested loop structure to print the pattern
- The outer loop should iterate through each row
- The inner loop should build each row with the correct number of stars
- Print each completed row
Example: if input is 3 rows and 4 columns, output should be:
****
****
****Cheat sheet
Nested loops are loops inside other loops:
for x in range(2):
for y in range(2):
print(x, y)
# Output:
# 0 0
# 0 1
# 1 0
# 1 1The inner loop completes all iterations for each iteration of the outer loop, similar to how a clock's minute hand completes a full cycle for each hour.
Try it yourself
# Get input for rows and columns
rows = int(input())
cols = int(input())
# Write your nested loops here
# Outer loop for rows
# Inner loop for columnsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2