DEV Community

mohd ibrahim
mohd ibrahim

Posted on

πŸ”„ Loops in Python: Why My Brain Kept Going in Circles

πŸŒ€ The "Infinite" Struggle: Making Loops Click

If you thought if/else was tricky, let me introduce you to the Loop.

When I first started, I understood the definition of a loop, but when it came to actually writing one? My brain just stalled. I either created a loop that never stopped (RIP my computer fans) or a loop that didn't run at all.


πŸ€– For vs. While: The Identity Crisis

I used to stare at the screen wondering: "Which one do I pick?" Here is how I finally broke them down in my head:

1. The for loop: The "List Follower"

I think of a for loop like a waiter at a table. It knows exactly how many people (items) are there, and it visits each one until the job is done.

  • The Breakthrough: Understanding that the variable (like i or item) changes automatically every time. You don't have to tell it to move to the next item; it just knows.

2. The while loop: The "Security Guard"

A while loop is like a security guard: "As long as this condition is true, keep doing the thing."

  • The Struggle: The dreaded Infinite Loop. If you forget to change the condition inside the loop, it stays true forever. My first while loop printed "Hello" 10,000 times before I figured out how to kill the terminal.

❌ The "Wrong" Way (The Infinite Loop)

This is what I did the first time. I set a condition, but I forgot to "change the world" inside the loop.

# Goal: Count to 5
counter = 1

while counter <= 5:
    print(f"Counting: {counter}")
    # Whoops! I forgot to add 1 to the counter.
    # This prints "Counting: 1" forever.
Enter fullscreen mode Exit fullscreen mode

βœ… The "Right" Way (The Fix)
The fix is simple, but it’s the logic that matters: you have to "update" the state so the condition eventually becomes False.

# Goal: Count to 5
counter = 1

while counter <= 5:
    print(f"Counting: {counter}")
    counter += 1  # The magic line that saves your CPU!
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ The "Aha!" Moment
The biggest breakthrough for me was realizing:

Use for when you know how many times you need to repeat (or you have a list/range).

Use while when you don't know exactly when you’ll stop (like waiting for a user to type "quit").


🎯 My New Strategy
Instead of guessing, I now ask myself three questions before I type a single line of code:

The Start: Where am I beginning?

The Goal: When do I need to stop?

The Step: How am I getting closer to that goal in every round?


πŸ’¬ Let’s Chat
If you’re learning Python: What was the first "infinite loop" mistake you made? And if you're a pro: What's the one thing you wish someone told you about loops when you started?

I'm still learning, so I'd love to hear your tips!

Top comments (0)