DEV Community

Aditya Sorathiya
Aditya Sorathiya

Posted on

🚀 Galactic Express: How Python Loops Saved the Universe!

A space adventure where 5,000 deliveries, one lazy alien, and a programmer discover the power of Python loops.


🌌 Chapter 1: The Impossible Mission

Year 3026. The Galactic Express delivery company had received its biggest order ever. 5,000 packages. 200 planets. One spaceship. Three extremely confused employees.

Captain Nova was checking the delivery list.

Captain Nova: “Bloop! We have 5,000 packages to deliver. Start delivering!”

Bloop: “Okay! I’ll write the same delivery instruction 5,000 times.”

Captain Nova: “WHAT?!”

Pixel, the spaceship’s programmer, entered the room.

Pixel: “Wait! Why repeat the same instruction thousands of times when Python can do it for us?”

Captain Nova: “Can Python deliver packages?”

Pixel: “Not physically. But it can repeat instructions.”

Captain Nova: “So it’s a delivery employee without a salary?”

Pixel: “Exactly.”

Today, we’ll learn how Python loops work!


🔁 Chapter 2: The FOR Loop — The Automated Delivery Employee

Pixel opened his laptop.

Pixel: “Let’s say we have 5 packages. We need to deliver each one.”

Instead of writing the same instruction repeatedly, we can use a for loop:

for package in range(1, 6):
    print("Delivering package", package)
Enter fullscreen mode Exit fullscreen mode

Output:

Delivering package 1
Delivering package 2
Delivering package 3
Delivering package 4
Delivering package 5
Enter fullscreen mode Exit fullscreen mode

Bloop: “WAIT! It delivered all five without me moving?!”

Pixel: “Yes. That’s a for loop.”

🧠 How does it work?

Let’s understand the important keywords:

  • for — starts a for loop.
  • package — a variable that receives each value.
  • in — tells Python where to get the values from.
  • range(1, 6) — generates numbers from 1 to 5.
  • : — marks the beginning of the loop’s body.
  • Indentation — tells Python which statements belong inside the loop.

⚠️ Important: range(1, 6) does not include 6. The ending number is excluded.

Captain Nova: “So if I write range(1, 100), it delivers 99 packages?”

Pixel: “Correct.”

Captain Nova: “I’M FIRING THE PERSON WHO INVENTED COUNTING!”

What if we have a list of planets?

A for loop can also iterate over items in a list:

planets = ["Mars", "Venus", "Jupiter", "Neptune"]

for planet in planets:
    print("Delivering to", planet)
Enter fullscreen mode Exit fullscreen mode

Output:

Delivering to Mars
Delivering to Venus
Delivering to Jupiter
Delivering to Neptune
Enter fullscreen mode Exit fullscreen mode

Bloop: “I like this loop. It even remembers the planet names!”

Pixel: “It doesn’t remember them. It takes each item from the list one at a time.”


⏳ Chapter 3: The WHILE Loop — The Stubborn Delivery Machine

Everything was going perfectly. Until Captain Nova noticed something.

Captain Nova: “We have 3 packages left. Keep delivering until there are none!”

Pixel: “This is a perfect situation for a while loop.”

A while loop repeats a block of code as long as its condition is True.

packages = 3

while packages > 0:
    print("Package delivered!")
    packages -= 1

print("All packages delivered!")
Enter fullscreen mode Exit fullscreen mode

Output:

Package delivered!
Package delivered!
Package delivered!
All packages delivered!
Enter fullscreen mode Exit fullscreen mode

Bloop: “How does it know when to stop?”

Pixel: “It checks the condition before every repetition.”

🧠 Understanding the keywords

  • while — starts a while loop.
  • packages > 0 — the condition that must be True.
  • : — marks the beginning of the loop body.
  • Indentation — identifies the statements inside the loop.
  • packages -= 1 — decreases the package count by one.
  • print() — displays the message.

⚙️ Let’s understand the execution:

  1. packages starts at 3.
  2. Python checks whether packages > 0.
  3. If True, it runs the loop body.
  4. The package count decreases.
  5. Python checks the condition again.
  6. When the condition becomes False, the loop stops.

Captain Nova: “What happens if we forget to decrease the package count?”

Pixel: “The loop might never stop!”

Bloop: “FREE INFINITE DELIVERY!”

Pixel: “No, Bloop. That’s called an infinite loop.”

💡 Remember: Make sure your while loop has a way to eventually make its condition False, unless an infinite loop is intentional.


🛑 Chapter 4: BREAK — The Emergency Stop Button

Suddenly, the spaceship received a warning.

🚨 WARNING: UNKNOWN PLANET DETECTED!

Captain Nova: “STOP THE DELIVERIES! WE DON’T KNOW WHAT’S THERE!”

Pixel: “We can use the break statement.”

The break statement immediately terminates the nearest enclosing loop.

planets = ["Mars", "Venus", "Unknown", "Jupiter"]

for planet in planets:
    if planet == "Unknown":
        print("Danger! Stopping deliveries!")
        break
    print("Delivering to", planet)
Enter fullscreen mode Exit fullscreen mode

Output:

Delivering to Mars
Delivering to Venus
Danger! Stopping deliveries!
Enter fullscreen mode Exit fullscreen mode

Bloop: “What happened to Jupiter?”

Pixel: “The loop stopped when it reached Unknown.”

Captain Nova: “Excellent! The emergency button actually works!”

💡 Remember: break completely exits the nearest loop. The remaining iterations are skipped.


⏭️ Chapter 5: CONTINUE — Skip This One!

The spaceship safely passed the unknown planet. But now Bloop had another problem.

Bloop: “Captain! Some planets are closed today. Should we cancel the entire mission?”

Pixel: “No! We can use continue.”

The continue statement skips the rest of the current iteration and moves to the next iteration.

planets = ["Mars", "Closed Planet", "Venus", "Jupiter"]

for planet in planets:
    if planet == "Closed Planet":
        print("Skipping this planet!")
        continue
    print("Delivering to", planet)
Enter fullscreen mode Exit fullscreen mode

Output:

Delivering to Mars
Skipping this planet!
Delivering to Venus
Delivering to Jupiter
Enter fullscreen mode Exit fullscreen mode

Captain Nova: “So it skips only the closed planet and continues with the others?”

Pixel: “Exactly!”

Bloop: “I wish my school had a continue statement.”

Captain Nova: “You would skip every Monday!”

⚔️ BREAK vs CONTINUE

Statement What it does
break Stops the entire nearest loop
continue Skips the current iteration

Pixel: “One stops the mission. The other skips one stop.”


🧩 Chapter 6: The Secret Ingredients of a Python Loop

Captain Nova was finally interested in programming.

Captain Nova: “Pixel! Tell me all the important keywords and concepts used in loops!”

Pixel: “Here is your crash course.”

1. for

Used to iterate over items in a sequence or iterable.

for number in range(3):
    print(number)
Enter fullscreen mode Exit fullscreen mode

2. in

Used to get values from an iterable.

for planet in ["Mars", "Venus"]:
    print(planet)
Enter fullscreen mode Exit fullscreen mode

3. while

Repeats code while a condition remains True.

count = 0
while count < 3:
    print(count)
    count += 1
Enter fullscreen mode Exit fullscreen mode

4. range()

A built-in function that generates a sequence of integers.

for number in range(1, 6):
    print(number)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

It can accept three arguments: range(start, stop, step)

for number in range(2, 11, 2):
    print(number)
Enter fullscreen mode Exit fullscreen mode

Output:

2
4
6
8
10
Enter fullscreen mode Exit fullscreen mode

5. break

Terminates the nearest enclosing loop.

6. continue

Skips the current iteration.

7. else

Python loops can also have an else block. The else block runs when the loop finishes normally, without being terminated by break.

for number in range(3):
    print(number)
else:
    print("Loop completed!")
Enter fullscreen mode Exit fullscreen mode

Output:

0
1
2
Loop completed!
Enter fullscreen mode Exit fullscreen mode

Captain Nova: “So loops have an else too?!”

Pixel: “Yes. Python likes surprises.”

8. Indentation

Indentation is essential in Python.

✅ Correct:

for number in range(3):
    print(number)
Enter fullscreen mode Exit fullscreen mode

❌ Incorrect:

for number in range(3):
print(number)
Enter fullscreen mode Exit fullscreen mode

The second example causes an IndentationError.

Pixel: “Python is very strict about indentation.”

Bloop: “Even Python has discipline. Interesting.”


🌠 Chapter 7: The Final Mission

The spaceship had one final task: Deliver 10 packages, but skip package number 4 and stop if package number 8 is reached.

Pixel wrote:

for package in range(1, 11):
    if package == 4:
        print("Skipping package 4")
        continue
    if package == 8:
        print("Mission stopped!")
        break
    print("Delivered package", package)
Enter fullscreen mode Exit fullscreen mode

Output:

Delivered package 1
Delivered package 2
Delivered package 3
Skipping package 4
Delivered package 5
Delivered package 6
Delivered package 7
Mission stopped!
Enter fullscreen mode Exit fullscreen mode

Captain Nova: “WE DID IT! ALL DELIVERIES COMPLETED!”

Pixel: “Actually, we stopped at package 8.”

Captain Nova: “THEN WHY IS THE MISSION REPORT GREEN?!”

Bloop: “Because I changed the status manually.”

Captain Nova: “BLOOOOOOP!!!”

And that’s how Python loops saved the Galactic Express from writing the same code thousands of times.


🎯 Quick Recap

  • for loop: Repeats over items in an iterable.
  • while loop: Repeats while a condition is True.
  • break: Terminates the nearest enclosing loop.
  • continue: Skips the current iteration.
  • range(): Generates a sequence of integers.
  • in: Gets values from an iterable.
  • else: Runs when a loop finishes normally without break.
  • Indentation: Defines the loop body.

💬 Your Turn!

Imagine you’re programming a spaceship. You need to count down from 5 to 1 and then print "Liftoff!"

Which loop would you use?

  • A) for loop
  • B) while loop
  • C) Both can do it!

Share your answer in the comments! And tell me: Which character was your favourite — Captain Nova, Pixel, or Bloop? 😂

Top comments (0)