For Loops

Back

Loading concept...

For Loops: Your Robot Helper That Never Gets Tired 🤖

Imagine you have a magical robot friend. You tell it ONE time what to do, and it does that thing over and over for you—perfectly, every single time. That’s what a for loop is in Python!


The Big Picture: Why Do We Need Loops?

Let’s say you want to say “Hello!” to 5 friends. Without a loop, you’d write:

print("Hello, friend 1!")
print("Hello, friend 2!")
print("Hello, friend 3!")
print("Hello, friend 4!")
print("Hello, friend 5!")

That’s 5 lines! What if you had 100 friends? 1000 friends? Your fingers would get SO tired!

With a for loop, you tell Python ONCE, and it repeats for you:

for i in range(5):
    print(f"Hello, friend {i+1}!")

Two lines. Done. Your robot helper does the rest! 🎉


1. For Loop Basics: Meet Your Robot Helper

Think of a for loop like giving instructions to a robot at a cookie factory:

“For EACH cookie on this tray, put chocolate chips on top.”

The robot picks up cookie 1, adds chips. Then cookie 2, adds chips. Then cookie 3… until ALL cookies are done!

The Magic Recipe

for item in collection:
    do_something_with(item)

Translation:

  • for = “Hey robot, start working!”
  • item = the thing you’re working with RIGHT NOW
  • in collection = the group of things to go through
  • do_something = what to do with each one

Your First For Loop

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I love {fruit}!")

Output:

I love apple!
I love banana!
I love cherry!

The robot:

  1. Grabs “apple” → prints “I love apple!”
  2. Grabs “banana” → prints “I love banana!”
  3. Grabs “cherry” → prints “I love cherry!”
  4. No more fruits? Robot stops!

2. The Range Function: Counting Made Easy

What if you don’t have a list of things, but you just want to count? Like doing jumping jacks?

range() creates numbers for you!

range(stop): Count from 0

for i in range(5):
    print(i)

Output: 0, 1, 2, 3, 4

Remember: Python starts counting at 0, and stops BEFORE the number you give it!

Think of it like a fence:

  • range(5) = 5 fence posts, numbered 0 through 4

range(start, stop): Pick Where to Begin

for i in range(2, 6):
    print(i)

Output: 2, 3, 4, 5

Start at 2, stop BEFORE 6.

range(start, stop, step): Skip Some Numbers

for i in range(0, 10, 2):
    print(i)

Output: 0, 2, 4, 6, 8

Count by 2s! Like skipping stones: 0, skip, 2, skip, 4…

Counting Backwards? Yes!

for i in range(5, 0, -1):
    print(i)

Output: 5, 4, 3, 2, 1

Rocket launch countdown! 🚀


3. Looping Through Collections: Lists, Strings, and More!

Your robot can walk through ANYTHING that has multiple items.

Looping Through a List

colors = ["red", "green", "blue"]

for color in colors:
    print(f"I see {color}")

Looping Through a String (Each Letter!)

A string is like a necklace of letters. The robot picks up each bead:

word = "HELLO"

for letter in word:
    print(letter)

Output:

H
E
L
L
O

Looping Through a Dictionary

pet_ages = {"dog": 3, "cat": 5, "fish": 1}

for pet in pet_ages:
    print(f"My {pet} is {pet_ages[pet]} years old")

Pro tip: Loop through both keys AND values:

for pet, age in pet_ages.items():
    print(f"My {pet} is {age} years old")

4. The Enumerate Function: Counting While You Loop

Sometimes you need to know: “Which item number am I on?”

Like a teacher calling roll: “Student #1: Alice. Student #2: Bob…”

enumerate() gives you BOTH the position AND the item!

students = ["Alice", "Bob", "Charlie"]

for index, name in enumerate(students):
    print(f"Student #{index}: {name}")

Output:

Student #0: Alice
Student #1: Bob
Student #2: Charlie

Start Counting from 1 (More Natural!)

for index, name in enumerate(students, start=1):
    print(f"Student #{index}: {name}")

Output:

Student #1: Alice
Student #2: Bob
Student #3: Charlie

Much better! People don’t usually start counting at zero. 😄


5. The Zip Function: Walking Two Dogs at Once

Imagine walking two dogs side by side. Left foot, right foot. Left dog, right dog. They move TOGETHER!

zip() lets you loop through TWO (or more) lists at the same time!

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]

for name, score in zip(names, scores):
    print(f"{name} scored {score}")

Output:

Alice scored 95
Bob scored 87
Charlie scored 92

What Happens If Lists Are Different Sizes?

zip() stops at the SHORTEST list. Like a three-legged race—both partners have to keep up!

a = [1, 2, 3, 4, 5]
b = ["x", "y"]

for num, letter in zip(a, b):
    print(num, letter)

Output:

1 x
2 y

Only 2 pairs, because b only has 2 items!

Zipping Three Lists? No Problem!

names = ["Alice", "Bob"]
ages = [25, 30]
cities = ["NYC", "LA"]

for name, age, city in zip(names, ages, cities):
    print(f"{name}, {age}, lives in {city}")

6. Nested Loops: A Loop INSIDE a Loop

Sometimes your robot needs a helper robot!

Think of a clock:

  • The hour hand goes around once
  • The minute hand goes around 60 times for EACH hour!

That’s a nested loop!

Simple Example: Rows and Columns

for row in range(3):
    for col in range(4):
        print("*", end=" ")
    print()  # New line after each row

Output:

* * * *
* * * *
* * * *

What happens:

  1. Outer loop says: “Row 0, go!”
  2. Inner loop prints 4 stars
  3. Outer loop says: “Row 1, go!”
  4. Inner loop prints 4 MORE stars
  5. And so on…

Real Example: Times Table

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i*j}")
    print("---")

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---

Warning: Don’t Go Too Deep!

Nested loops multiply!

  • 1 loop of 100 = 100 steps
  • 2 nested loops of 100 = 100 × 100 = 10,000 steps!
  • 3 nested loops of 100 = 1,000,000 steps!

Keep it simple when you can. 😊


Quick Recap: Your Loop Toolbox

graph TD A["FOR LOOPS"] --> B["Basics"] A --> C["range"] A --> D["Collections"] A --> E["enumerate"] A --> F["zip"] A --> G["Nested"] B --> B1["for item in list"] C --> C1["range#40;5#41;<br>range#40;2,6#41;<br>range#40;0,10,2#41;"] D --> D1["strings, lists,<br>dictionaries"] E --> E1["index + item<br>together"] F --> F1["two lists<br>side by side"] G --> G1["loop inside<br>a loop"]

The Magic Moment

You now have a robot army! 🤖🤖🤖

  • Basic loops do repetitive work
  • range() counts for you
  • Collections let you walk through anything
  • enumerate() counts as you go
  • zip() walks through multiple things together
  • Nested loops handle rows, columns, and grids

No more typing the same thing 100 times. Tell Python ONCE, and let it repeat!

That’s the power of for loops.

Now go build something amazing! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.