PYTHON FOR LOOP

Iterate over sequences like lists, tuples, dictionaries, and ranges to automate repetitive tasks and data processing in Python.

🔄 What is a For Loop in Python?

A Python for loop is used for iterating over an iterable sequence (such as a list, tuple, dictionary, set, or string). Unlike for loops in other programming languages, Python's for loop acts more like an iterator method. It is heavily utilized in inventory management systems, automated reporting, batch file processing, billing engines, and user notifications.

1. Basic For Loop Syntax & Range Function
The range() function allows you to generate a sequence of numbers easily, which is commonly used to repeat code execution a specific number of times.
Python
# Iterate numbers from 0 to 4
for i in range(5):
    print("Count:", i)
Output: Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
2. How For Loop Works (Execution Flow)
Start Loop & Fetch Next Item from Sequence
↓
Are there items left in the sequence?
↓
TRUE → Assign item to variable & execute indented code block
↓
FALSE → Exit loop and proceed to next program statement
Real-Time Example 1: E-Commerce Inventory Stock Check
Iterate through an inventory dictionary to flag items running low on stock.
Python
stock_levels = {"Sugar": 15, "Flour": 4, "Rice": 25, "Oil": 8}

print("Low Stock Alerts:")
for item, qty in stock_levels.items():
    if qty < 10:
        print(f"Warning: {item} is running low ({qty} units left)")
Output: Low Stock Alerts: Warning: Flour is running low (4 units left) Warning: Oil is running low (8 units left)
Real-Time Example 2: Retail Billing & Total Calculation
Calculate grand total cart amount by summing up item prices from a shopping list.
Python
cart_prices = [450, 1200, 300, 850, 150]
total_bill = 0

for price in cart_prices:
    total_bill += price

print("Total Cart Amount: ₹", total_bill)
Output: Total Cart Amount: ₹ 2950
Real-Time Example 3: Student Attendance Tracker
Loop through a roster dictionary to count present students for daily administrative logs.
Python
attendance = {"Rahul": "Present", "Priya": "Absent", "Amit": "Present", "Sneha": "Present"}
present_count = 0

for student, status in attendance.items():
    if status == "Present":
        present_count += 1

print("Total Students Present:", present_count)
Output: Total Students Present: 3
Real-Time Example 4: Employee Payroll Salary Increment
Iterate through an employee salary list to process annual compensation revisions.
Python
salaries = [35000, 48000, 52000, 60000]
updated_salaries = []

for sal in salaries:
    new_sal = sal * 1.10  # 10% increment
    updated_salaries.append(int(new_sal))

print("Revised Salaries:", updated_salaries)
Output: Revised Salaries: [38500, 52800, 57200, 66000]
Real-Time Example 5: ATM Multi-User Balance Validation
Verify account statuses and flag accounts requiring minimum balance maintenance.
Python
account_balances = [12000, 2500, 45000, 800, 15000]

for idx, balance in enumerate(account_balances, start=1):
    if balance < 3000:
        print(f"Account {idx}: Penalty applied for low balance (₹{balance})")
    else:
        print(f"Account {idx}: Status Normal (₹{balance})")
Output: Account 1: Status Normal (₹12000) Account 2: Penalty applied for low balance (₹2500) Account 3: Status Normal (₹45000) Account 4: Penalty applied for low balance (₹800) Account 5: Status Normal (₹15000)
Real-Time Example 6: Email Domain Validation Filter
Scan user database registration lists to filter and collect corporate domain emails.
Python
email_list = ["john@gmail.com", "sarah@company.com", "admin@yahoo.com", "dave@company.com"]
corporate_users = []

for email in email_list:
    if email.endswith("@company.com"):
        corporate_users.append(email)

print("Verified Corporate Emails:", corporate_users)
Output: Verified Corporate Emails: ['sarah@company.com', 'dave@company.com']
Real-Time Example 7: Restaurant Table Booking Tracker
Loop through reservation tokens to allocate tables for waiting guests automatically.
Python
waiting_queue = ["Table-1", "Table-2", "Table-3"]

print("Seating Guests:")
for table in waiting_queue:
    print(f"Allocating {table} to next family in queue.")
Output: Seating Guests: Allocating Table-1 to next family in queue. Allocating Table-2 to next family in queue. Allocating Table-3 to next family in queue.
Real-Time Example 8: File Batch Processing Simulation
Process batches of uploaded image file names to convert or compress formats.
Python
uploaded_files = ["photo1.png", "logo.jpg", "banner.png", "icon.svg"]

for file in uploaded_files:
    if file.endswith((".png", ".jpg")):
        print(f"Processing image compression for: {file}")
    else:
        print(f"Skipping unsupported format: {file}")
Output: Processing image compression for: photo1.png Processing image compression for: logo.jpg Processing image compression for: banner.png Skipping unsupported format: icon.svg