🔄 What is a For Loop in Python?
A Python for loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string). It is commonly used in inventory systems, data reporting, batch 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 often used to repeat a block of code 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 (Flow)
Start Loop & Fetch Next Item from Sequence
↓
Are there items left in the sequence?
↓
TRUE → Assign item to variable & execute code block
↓
FALSE → Exit loop and proceed to next program statement
Real-Time Example 1: E-Commerce Inventory Stock Check
Iterate through an inventory list to identify 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 the grand total bill amount by summing up item prices from a cart.
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 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 list to process annual salary 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 a user database registration list to find 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 seat 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 a batch 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
Real-Time Example 9: Exam Grade Analytics & Pass Counter
Analyze a list of student marks to calculate how many candidates passed.
Python
exam_scores = [78, 45, 92, 33, 60, 88, 54]
passed_students = 0
for score in exam_scores:
if score >= 50:
passed_students += 1
print("Total Candidates Passed:", passed_students)
print("Total Candidates Failed:", len(exam_scores) - passed_students)
Output:
Total Candidates Passed: 5
Total Candidates Failed: 2
Real-Time Example 10: Bulk Rate Pricing Matrix
Generate a bulk rate pricing matrix or multiplication table for service units.
Python
base_rate = 150
print("Bulk Rate Pricing Table (1 to 5 units):")
for unit in range(1, 6):
cost = unit * base_rate
print(f"{unit} Unit(s) = ₹{cost}")
Output:
Bulk Rate Pricing Table (1 to 5 units):
1 Unit(s) = ₹150
2 Unit(s) = ₹300
3 Unit(s) = ₹450
4 Unit(s) = ₹600
5 Unit(s) = ₹750
Summary of Python For Loops
- Iteration: For loops automate repetitive tasks across any iterable sequence like lists, tuples, or dictionaries.
- Range: Use `range(start, stop, step)` to loop through specific number sequences.
- Efficiency: Combined with conditional statements, for loops form the core engine for data filtering, validation, and batch reporting.