Python Loops Explained (For & While)
📌 Quick Info
- Topic: Loops in Python (For & While)
- Target Audience: Beginners who know if-else
- Goal: Understand when to use for vs while
1. Introduction
"After learning if-else, I could make my code decide things. But I still had to write the same line 10 times for 10 items. Then I discovered loops — and everything got shorter."
2. The Problem (Without Loops)
print("Item 1")
print("Item 2")
print("Item 3")
print("Item 4")
print("Item 5")
Problem: Imagine doing this for 100 times.
3. The Solution (For Loop)
for i in range(1, 6):
print(f"Item {i}")
Output:
Item 1
Item 2
Item 3
Item 4
Item 5
4. The Solution (While Loop)
count = 1
while count <= 5:
print(f"Item {count}")
count += 1
Output:
Item 1
Item 2
Item 3
Item 4
Item 5
5. For vs While: When to Use Which
| Use for when... | Use while when... |
|---|---|
| You know how many times | You don't know how many times |
| Looping through a list | Looping until a condition changes |
6. What I learned
- Loops save me from repeating code.
- for is for know counts.
- while is for unknown counts
- range (1,6) goes from 1 to 5- it stops before the second number. So, range (1,6) gives you 1,2,3,4,5
7. Conclusion
Loops felt confusing until i wrote them 5 times. Now i use them almost everywhere
Top comments (0)