Python For Loops

Master iteration and repetition in Python programming

šŸ” What are For Loops?

A for loop in Python lets you repeat code for each item in a sequence. It's perfect for working with lists, strings, and other collections of data.


# Simple for loop example
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# orange
                                    
for
Keyword
in
Operator
Iterate
Collections

Basic For Loop Syntax

Let's start with the simplest for loop examples:

Basic For Loop
# Basic syntax: for item in collection:
fruits = ["apple", "banana", "cherry"]

print("My favorite fruits:")
for fruit in fruits:
    print(f"- {fruit}")

# Output:
# My favorite fruits:
# - apple
# - banana
# - cherry

# Looping through a string
word = "Python"
print(f"\nLetters in '{word}':")
for letter in word:
    print(letter)

# Output: P, y, t, h, o, n (each on new line)

The range() Function

Use range() to loop through a sequence of numbers:

1ļøāƒ£

range(stop)

Numbers from 0 to stop-1

for i in range(5):
    print(i)  # 0, 1, 2, 3, 4
2ļøāƒ£

range(start, stop)

Numbers from start to stop-1

for i in range(2, 6):
    print(i)  # 2, 3, 4, 5
3ļøāƒ£

range(start, stop, step)

Numbers with custom step size

for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8
Range Examples
# Counting from 1 to 5
print("Counting up:")
for i in range(1, 6):
    print(f"Count: {i}")

# Counting down
print("\nCountdown:")
for i in range(5, 0, -1):
    print(f"T-minus {i}")
print("Blast off! šŸš€")

# Even numbers
print("\nEven numbers from 0 to 10:")
for i in range(0, 11, 2):
    print(i, end=" ")  # Print on same line
print()  # New line

# Multiplication table
number = 7
print(f"\nMultiplication table for {number}:")
for i in range(1, 11):
    result = number * i
    print(f"{number} Ɨ {i} = {result}")

Loop Control: break and continue

Control the flow of your loops with break and continue :

šŸ›‘

break

Exit the loop completely

for i in range(10):
    if i == 5:
        break
    print(i)  # 0, 1, 2, 3, 4
ā­ļø

continue

Skip to next iteration

for i in range(5):
    if i == 2:
        continue
    print(i)  # 0, 1, 3, 4
Break and Continue Examples
# Finding the first even number
numbers = [1, 3, 7, 8, 9, 12, 15]
print("Looking for first even number:")
for num in numbers:
    if num % 2 == 0:
        print(f"Found first even number: {num}")
        break
    print(f"{num} is odd, continuing...")

# Skip negative numbers
numbers = [-2, -1, 0, 1, 2, 3, -4, 5]
print("\nProcessing only positive numbers:")
for num in numbers:
    if num <= 0:
        continue  # Skip non-positive numbers
    print(f"Processing: {num}")

# Password validation with break
attempts = ["123", "password", "admin", "secret123"]
correct_password = "secret123"

print("\nPassword attempts:")
for attempt in attempts:
    print(f"Trying: {attempt}")
    if attempt == correct_password:
        print("āœ… Access granted!")
        break
    else:
        print("āŒ Incorrect password")
else:
    # This runs if loop completes without break
    print("šŸ”’ Access denied - too many failed attempts")

The else Clause with For Loops

The else clause runs when the loop completes normally (without break ):

For-Else Examples
# Example 1: Loop completes normally
print("Counting to 3:")
for i in range(1, 4):
    print(i)
else:
    print("Loop finished without breaking!")

print("\n" + "="*30)

# Example 2: Loop breaks early
print("Looking for number 7:")
numbers = [1, 3, 5, 7, 9]
for num in numbers:
    print(f"Checking {num}")
    if num == 7:
        print("Found 7! Breaking...")
        break
else:
    print("7 not found in the list")

print("\n" + "="*30)

# Example 3: Practical use - Prime number checker
def is_prime(n):
    """Check if a number is prime using for-else."""
    if n < 2:
        return False
    
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False  # Found a divisor, not prime
    else:
        return True  # No divisors found, is prime

# Test prime checker
test_numbers = [2, 3, 4, 17, 25, 29]
print("Prime number test:")
for num in test_numbers:
    result = "prime" if is_prime(num) else "not prime"
    print(f"{num} is {result}")

Nested Loops

Use loops inside other loops for complex iterations:

Nested Loop Examples
# Simple nested loop
print("Multiplication table (1-3):")
for i in range(1, 4):
    for j in range(1, 4):
        product = i * j
        print(f"{i} Ɨ {j} = {product}")
    print()  # Empty line after each row

# Creating a pattern
print("Star pattern:")
for row in range(1, 6):
    for col in range(row):
        print("*", end="")
    print()  # New line after each row

# Working with 2D data
students = [
    ["Alice", [85, 90, 78]],
    ["Bob", [92, 88, 95]],
    ["Charlie", [76, 82, 89]]
]

print("\nStudent grades:")
for student_name, grades in students:
    print(f"{student_name}:")
    total = 0
    for grade in grades:
        print(f"  Grade: {grade}")
        total += grade
    average = total / len(grades)
    print(f"  Average: {average:.1f}")
    print()

# Finding pairs
numbers = [1, 2, 3, 4]
print("All possible pairs:")
for i in numbers:
    for j in numbers:
        if i != j:  # Don't pair with itself
            print(f"({i}, {j})")

Real-World Example: Data Processing

Let's see how for loops are used in practical data processing scenarios:

Sales Data Analysis
# Sales data processing system
sales_data = [
    {"product": "Laptop", "price": 1200, "quantity": 5, "category": "Electronics"},
    {"product": "Mouse", "price": 25, "quantity": 20, "category": "Electronics"},
    {"product": "Keyboard", "price": 75, "quantity": 15, "category": "Electronics"},
    {"product": "Chair", "price": 300, "quantity": 8, "category": "Furniture"},
    {"product": "Desk", "price": 500, "quantity": 3, "category": "Furniture"},
    {"product": "Book", "price": 20, "quantity": 50, "category": "Education"}
]

def analyze_sales_data(data):
    """Comprehensive sales data analysis using for loops."""
    
    # Initialize tracking variables
    total_revenue = 0
    category_sales = {}
    high_value_items = []
    low_stock_items = []
    
    print("=== SALES DATA ANALYSIS ===")
    print(f"Analyzing {len(data)} products...\n")
    
    # Process each product
    for item in data:
        product = item["product"]
        price = item["price"]
        quantity = item["quantity"]
        category = item["category"]
        
        # Calculate item revenue
        item_revenue = price * quantity
        total_revenue += item_revenue
        
        # Track category sales
        if category in category_sales:
            category_sales[category] += item_revenue
        else:
            category_sales[category] = item_revenue
        
        # Identify high-value items (>$1000 revenue)
        if item_revenue > 1000:
            high_value_items.append({
                "product": product,
                "revenue": item_revenue
            })
        
        # Identify low stock items (<10 quantity)
        if quantity < 10:
            low_stock_items.append({
                "product": product,
                "quantity": quantity
            })
        
        # Print item details
        print(f"šŸ“¦ {product}")
        print(f"   Price: ${price:,.2f}")
        print(f"   Quantity: {quantity}")
        print(f"   Revenue: ${item_revenue:,.2f}")
        print(f"   Category: {category}")
        print()
    
    # Display summary results
    print("=" * 50)
    print("šŸ“Š SUMMARY RESULTS")
    print("=" * 50)
    
    print(f"šŸ’° Total Revenue: ${total_revenue:,.2f}")
    print()
    
    # Category breakdown
    print("šŸ“ˆ Revenue by Category:")
    for category, revenue in category_sales.items():
        percentage = (revenue / total_revenue) * 100
        print(f"   {category}: ${revenue:,.2f} ({percentage:.1f}%)")
    print()
    
    # High-value items
    if high_value_items:
        print("🌟 High-Value Items (>$1000 revenue):")
        for item in high_value_items:
            print(f"   {item['product']}: ${item['revenue']:,.2f}")
    else:
        print("🌟 No high-value items found")
    print()
    
    # Low stock alerts
    if low_stock_items:
        print("āš ļø  Low Stock Alerts (<10 items):")
        for item in low_stock_items:
            print(f"   {item['product']}: {item['quantity']} remaining")
    else:
        print("āœ… All items have adequate stock")
    print()
    
    # Find best and worst performing categories
    best_category = max(category_sales, key=category_sales.get)
    worst_category = min(category_sales, key=category_sales.get)
    
    print("šŸ† Performance Highlights:")
    print(f"   Best Category: {best_category} (${category_sales[best_category]:,.2f})")
    print(f"   Needs Attention: {worst_category} (${category_sales[worst_category]:,.2f})")

# Run the analysis
analyze_sales_data(sales_data)

# Additional example: Generate report for specific category
def category_report(data, target_category):
    """Generate detailed report for a specific category."""
    
    print(f"\nšŸ“‹ DETAILED REPORT: {target_category.upper()}")
    print("=" * 40)
    
    category_items = []
    for item in data:
        if item["category"] == target_category:
            category_items.append(item)
    
    if not category_items:
        print(f"No items found in {target_category} category")
        return
    
    # Sort by revenue (highest first)
    category_items.sort(key=lambda x: x["price"] * x["quantity"], reverse=True)
    
    print(f"Found {len(category_items)} items:")
    for i, item in enumerate(category_items, 1):
        revenue = item["price"] * item["quantity"]
        print(f"{i}. {item['product']}")
        print(f"   Revenue: ${revenue:,.2f}")
        print(f"   Stock: {item['quantity']} units")
        print()

# Generate category report
category_report(sales_data, "Electronics")

Advanced Iteration: enumerate() and zip()

Use built-in functions for more sophisticated iteration patterns:

Enumerate and Zip Examples
# enumerate() - get index and value
fruits = ["apple", "banana", "cherry", "date"]

print("Using enumerate():")
for index, fruit in enumerate(fruits):
    print(f"{index + 1}. {fruit}")

# enumerate() with custom start
print("\nWith custom start:")
for position, fruit in enumerate(fruits, start=1):
    print(f"Position {position}: {fruit}")

# zip() - iterate over multiple lists simultaneously
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Tokyo"]

print("\nUsing zip():")
for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} years old and lives in {city}")

# Practical example: Processing parallel data
products = ["Laptop", "Mouse", "Keyboard"]
prices = [1200, 25, 75]
stock = [5, 20, 15]

print("\nInventory Report:")
print("-" * 40)
for i, (product, price, quantity) in enumerate(zip(products, prices, stock), 1):
    total_value = price * quantity
    status = "āœ… In Stock" if quantity > 10 else "āš ļø Low Stock"
    
    print(f"{i}. {product}")
    print(f"   Price: ${price}")
    print(f"   Stock: {quantity} units {status}")
    print(f"   Total Value: ${total_value}")
    print()

# Creating dictionaries from lists
keys = ["name", "age", "city"]
values = ["David", 28, "Paris"]

person = {}
for key, value in zip(keys, values):
    person[key] = value

print(f"Created person: {person}")

# Alternative using dict() and zip()
person2 = dict(zip(keys, values))
print(f"Alternative method: {person2}")