1 of 6
A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.
for i in range(3): # Outer loop: runs 3 times for j in range(2): # Inner loop: runs 2 times PER outer iteration print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
Think of it like clock hands β the inner loop is the minute hand (spins fast) and the outer loop is the hour hand (moves after the minute hand completes a full cycle).
The total number of times the inner code runs = outer Γ inner.
for i in range(4): # 4 times for j in range(3): # 3 times each print("*") # Runs 4 Γ 3 = 12 times
rows = 3 cols = 5 for r in range(rows): for c in range(cols): print("*", end=" ") print() # New line after each row
Output:
* * * * *
* * * * *
* * * * *
The end=" " makes print stay on the same line. The print() after the inner loop moves to the next line.
for i in range(1, 6): for j in range(i): print("*", end=" ") print()
Output:
*
* *
* * *
* * * *
* * * * *
The inner loop runs i times β so row 1 gets 1 star, row 2 gets 2 stars, etc.
for i in range(1, 6): for j in range(1, 6): print(f"{i * j:4}", end="") print()
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
teams = ["Red", "Blue"] players = ["Alex", "Sam", "Jordan"] for team in teams: for player in players: print(f"{player} joins {team} team")
Output:
Alex joins Red team
Sam joins Red team
Jordan joins Red team
Alex joins Blue team
Sam joins Blue team
Jordan joins Blue team
break in Nested Loopsbreak only exits the inner loop, not the outer one:
for i in range(3): for j in range(5): if j == 2: break # Only breaks the inner loop print(f"i={i}, j={j}") print(f"--- Done with i={i} ---")
Output:
i=0, j=0
i=0, j=1
--- Done with i=0 ---
i=1, j=0
i=1, j=1
--- Done with i=1 ---
i=2, j=0
i=2, j=1
--- Done with i=2 ---
break only exits the innermost loopβ Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit