Nested Loops

STEP 3 β€” Nested Loops (a.k.a. Loops Having Loops as Pets)

Alright coder, buckle up.

Because this is the moment your loops stop being solo performers and start forming a loop orchestra.

A nested loop is simply:

A loop… inside another loop.

Yes.

It’s exactly as wild as it sounds.


1. What Is a Nested Loop?

A nested loop is when one loop runs, and inside it, another loop runs for every step.

It’s like:

  • Outer loop: β€œI’ll do this 3 times.”
  • Inner loop: β€œCool, I’ll do MY thing 5 times EACH time you run.”

Total chaos.

Total power.


2. Example: Printing Coordinates

for x in range(3):
    for y in range(2):
        print(x, y)

This prints every combination of x and y.

Your loop is now generating coordinates like a tiny game engine.

Click Run

3. Example: Looping Through a Grid

grid = [
    ["grass", "grass", "tree"],
    ["water", "grass", "rock"]
]

for row in grid:
    for tile in row:
        print("Tile:", tile)

Your loop now explores a map like a brave adventurer.

Minus the sword.

And the bravery.

Click Run

4. Why Nested Loops Matter

Nested loops let you:

  • scan game maps
  • check enemy positions
  • build crafting systems
  • generate levels
  • loop through lists inside lists
  • create patterns, grids, and combinations

This is the moment your code becomes multidimensional.


Practice (Your Turn!)

Mini-Challenge

Loop through this list:

items = [["potion", "elixir"], ["sword", "shield"]]

Print each item.

Modify and Run

Boom.

Your loop now handles nested lists like a pro chef handling layered lasagna.

You now command:

  • loops
  • loops inside loops
  • loops that loop while looping

Your code is officially doing gymnastics.

Ready for Step 4, the final boss of Unit 7, where we combine EVERYTHING β€” conditions, breaks, continues, and nested loops β€” into full game systems.