Welcome to Day 10 of the 100 Days of Python series!
Today we’ll dive into the incredibly useful for loop, and the built-in range() function — two tools that let you repeat actions and iterate over sequences efficiently.
Let’s explore how to use them and where they shine. 🧠
📦 What You'll Learn
- What a forloop is
- How range()works
- Looping over numbers, strings, and lists
- Using break,continue, andelsein loops
- Real-life use cases
  
  
  🔄 What Is a for Loop?
A for loop lets you iterate over a sequence (like a list, string, or range of numbers) and execute a block of code for each item.
Basic Syntax:
for item in sequence:
    # do something with item
  
  
  🔢 The range() Function
range() generates a sequence of numbers. It’s perfect for looping a specific number of times.
for i in range(5):
    print(i)
Output:
0
1
2
3
4
  
  
  range(start, stop[, step]):
- 
start: where to begin (default: 0)
- 
stop: where to end (exclusive)
- 
step: increment (default: 1)
Example:
for i in range(1, 6):
    print(i)  # 1 to 5
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8
🔁 Looping Over Strings and Lists
You can use for to iterate through any iterable (lists, strings, tuples, etc.)
Strings:
for letter in "Python":
    print(letter)
Lists:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")
  
  
  🧼 Using break and continue
  
  
  break: Exit the loop early
  
  
  continue: Skip to the next iteration
for num in range(10):
    if num == 5:
        break  # stops at 5
    print(num)
for num in range(10):
    if num % 2 == 0:
        continue  # skips even numbers
    print(num)
  
  
  ✨ Bonus: for + else
Python allows an optional else after a for loop. It runs only if the loop completes normally (no break).
for i in range(3):
    print(i)
else:
    print("Finished loop without break.")
🔧 Real-World Example 1: Countdown with Range
for seconds in range(5, 0, -1):
    print(seconds)
print("Go!")
📊 Real-World Example 2: Sum of Numbers
total = 0
for num in range(1, 11):
    total += num
print("Sum is:", total)
🧠 Real-World Example 3: Finding an Item
names = ["Alice", "Bob", "Charlie"]
search = "Bob"
for name in names:
    if name == search:
        print("Found:", name)
        break
else:
    print("Name not found.")
🚀 Recap
Today you learned:
- How to use forloops to iterate over data
- How range()helps generate numeric sequences
- Looping over strings, lists, and more
- Using break,continue, andelsewith loops
- Practical examples like sum, search, and countdowns
 
 
              
 
    
Top comments (0)