DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

🔁 Loops Explained Like You're 5

A repeating alarm clock

Day 23 of 149

👉 Full deep-dive with code examples


The Alarm Clock

Your alarm rings every morning at 7 AM.

It doesn't ring once and forget. It repeats every day!

Loops are code that repeats!


Without Loops (Painful)

print("Hello 1")
print("Hello 2")
print("Hello 3")
print("Hello 4")
print("Hello 5")
# ... 95 more lines 😫
Enter fullscreen mode Exit fullscreen mode

With Loops (Easy!)

for i in range(100):
    print("Hello", i)
Enter fullscreen mode Exit fullscreen mode

Done in 2 lines! 🎉


Types of Loops

For Loop: "Do this exactly 10 times"

for i in range(10):
    print(i)
Enter fullscreen mode Exit fullscreen mode

While Loop: "Keep doing this until something changes"

while hungry:
    eat_snack()
Enter fullscreen mode Exit fullscreen mode

In One Sentence

Loops repeat code automatically instead of you copying and pasting the same thing over and over.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)