The for Loop

STEP 3 β€” The for Loop (a.k.a. The Loop That Actually Knows What It’s Doing)

Ohhh yes β€” Step 3 is where the organized, responsible, straight-A student of loops finally shows up. If the while loop is chaotic energy, the for loop is the kid who color-codes their notes and reminds the teacher about homework.

Let’s unleash it.

Welcome to the for loop, the loop that doesn’t spiral out of control like a while loop on too much caffeine. This loop knows exactly how many times it’s going to run before it even starts.

  • It’s predictable.
  • It’s reliable.
  • It’s the loop your parents wish you were.

1. What a for Loop Does

A for loop repeats code for each item in something:

  • each number
  • each item in a list
  • each letter in a word
  • each enemy in a wave
  • each snack in your backpack (hopefully not melted)

It’s perfect for games because so many things come in groups:

  • inventory items
  • enemy lists
  • quest objectives
  • levels
  • turns in a battle

If it’s a collection, the for loop is ready to march through it like a tiny, polite army.


2. Basic Structure

for item in collection:
    # do something with item

Python is basically saying:

β€œFor each thing in this group, I’ll run this code. No drama.”


3. Example β€” Looping Through an Inventory

inventory = ["sword", "potion", "map"]

for item in inventory:
    print("You have:", item)
Click Run
Output:
  • You have: sword
    You have: potion
    You have: map

Your game is now smart enough to check everything the player owns β€” without you writing
three separate print statements like a caveman.


4. Example β€” Looping a Fixed Number of Times

for i in range(5):
    print("Enemy approaching!")
Click Run

This prints the message five times.
Because range(5) creates a list like:
0, 1, 2, 3, 4
The loop runs once for each number.
No infinite chaos.
No drama.
Just clean repetition.


5. Example: Looping Through Enemy Names

enemies = ["goblin", "orc", "slime"]

for enemy in enemies:
    print("A wild", enemy, "appears!")
Click Run

Your game now introduces enemies like it’s hosting a fantasy talent show.


Practice (Your Turn!)

Mini Challenge

Challenge:
Given this list:

spells = ["fireball", "ice blast", "heal"]

Write a loop that prints:

Casting: <spell> for each spell.

Modify and Run

Boom.
You just looped through a spellbook like a pro wizard.
Ready for Step 4, where we combine while, for, lists, and loop controls to build real
gameplay systems β€” enemy waves, turn cycles, and more.