Python Loop Examples with Real-World Order Processing
The best way to master loops is to solve real problems. All examples below work on one list of e-commerce orders, the kind of data you get from a database or an API. Each problem is solved with a for loop and, where useful, a while loop.
The Sample Data
orders = [
{"id": 101, "amount": 5000, "status": "Completed"},
{"id": 102, "amount": 0, "status": "Cancelled"},
{"id": 103, "amount": 15000, "status": "Completed"},
{"id": 104, "amount": 2000, "status": "Pending"},
{"id": 105, "amount": 25000, "status": "Completed"},
{"id": 106, "amount": 5000, "status": "Completed"},
{"id": 107, "amount": 13000, "status": "Pending"},
{"id": 108, "amount": 4500, "status": "Completed"},
{"id": 109, "amount": 14500, "status": "Cancelled"}
]
Example 1: Process the large orders using for loop
Process only the orders >= 10000 and ignore the cancelled orders
for order in orders:
if order["status"] == "Cancelled":
continue
if order["amount"] >= 10000:
print("Large Order:", order["id"], order["amount"])
Example 2: Same requirement using WHILE loop
i = 0
while i < len(orders):
order = orders[i]
i = i + 1 # increment before continue, otherwise infinite loop
if order["status"] == "Cancelled":
continue
if order["amount"] >= 10000:
print("Large Order:", order["id"], order["amount"])
Example 3: Calculate total revenue of Completed orders using for loop
total_revenue = 0
for order in orders:
if order["status"] == "Completed":
total_revenue = total_revenue + order["amount"]
print("Total Revenue:", total_revenue)
Example 4: Calculate total revenue of Completed orders using WHILE loop
total_revenue = 0
i = 0
while i < len(orders):
if orders[i]["status"] == "Completed":
total_revenue = total_revenue + orders[i]["amount"]
i = i + 1
print("Total Revenue:", total_revenue)
Example 5: Count the orders by status using for loop
completed_count = 0
pending_count = 0
cancelled_count = 0
for order in orders:
if order["status"] == "Completed":
completed_count = completed_count + 1
elif order["status"] == "Pending":
pending_count = pending_count + 1
elif order["status"] == "Cancelled":
cancelled_count = cancelled_count + 1
print("Completed:", completed_count)
print("Pending:", pending_count)
print("Cancelled:", cancelled_count)
Example 6: Count the orders by status using a dictionary (FOR loop)
status_count = {}
for order in orders:
status = order["status"]
status_count[status] = status_count.get(status, 0) + 1
print(status_count)
Example 7: Find the first Pending order and stop searching (FOR loop + break)
for order in orders:
if order["status"] == "Pending":
print("First Pending Order:", order["id"], order["amount"])
break
Example 8: Search an order by id using WHILE loop + break
search_id = 105
i = 0
found = False
while i < len(orders):
if orders[i]["id"] == search_id:
print("Order Found:", orders[i])
found = True
break
i = i + 1
if not found:
print("Order", search_id, "not found")
Example 9: For-else -> else block runs only when loop is NOT broken
search_id = 200
for order in orders:
if order["id"] == search_id:
print("Order Found:", order)
break
else:
print("Order", search_id, "not found")
Example 10: Find the highest and lowest order amount (ignore Cancelled)
highest_order = None
lowest_order = None
for order in orders:
if order["status"] == "Cancelled":
continue
if highest_order is None or order["amount"] > highest_order["amount"]:
highest_order = order
if lowest_order is None or order["amount"] < lowest_order["amount"]:
lowest_order = order
print("Highest Order:", highest_order["id"], highest_order["amount"])
print("Lowest Order:", lowest_order["id"], lowest_order["amount"])
Example 11: Collect the large order ids into a new list
large_order_ids = []
for order in orders:
if order["status"] != "Cancelled" and order["amount"] >= 10000:
large_order_ids.append(order["id"])
print("Large Order Ids:", large_order_ids)
Example 12: Same as above using List Comprehension (one line for loop)
large_order_ids = [order["id"] for order in orders
if order["status"] != "Cancelled" and order["amount"] >= 10000]
print("Large Order Ids:", large_order_ids)
Example 13: Print orders with serial number using enumerate()
for index, order in enumerate(orders, start=1):
print(index, "->", order["id"], order["amount"], order["status"])
Example 14: Apply 10% discount on Completed orders >= 10000
for order in orders:
if order["status"] == "Completed" and order["amount"] >= 10000:
discount = order["amount"] * 10 / 100
final_amount = order["amount"] - discount
print("Order:", order["id"], "Amount:", order["amount"],
"Discount:", discount, "Final Amount:", final_amount)
Example 15: Process Pending orders one by one until none left (WHILE loop)
pending_orders = [order for order in orders if order["status"] == "Pending"]
while pending_orders: # runs while list is not empty
order = pending_orders.pop(0) # take the first pending order
print("Processing Pending Order:", order["id"], "-> marked as Completed")
print("Pending orders left:", len(pending_orders))
Example 16: Stop processing once the daily target of 40000 is reached (WHILE loop)
daily_target = 40000
collected = 0
i = 0
while i < len(orders) and collected < daily_target:
if orders[i]["status"] == "Completed":
collected = collected + orders[i]["amount"]
print("Added Order:", orders[i]["id"], "Collected so far:", collected)
i = i + 1
print("Target reached:", collected >= daily_target)
Example 17: Group the orders by status (nested data using for loop)
grouped_orders = {}
for order in orders:
status = order["status"]
if status not in grouped_orders:
grouped_orders[status] = []
grouped_orders[status].append(order["id"])
for status, ids in grouped_orders.items():
print(status, "->", ids)
Example 18: Process orders in reverse order (latest order first)
for order in reversed(orders):
print(order["id"], order["amount"])
Example 19: Same reverse processing using WHILE loop
i = len(orders) - 1
while i >= 0:
print(orders[i]["id"], orders[i]["amount"])
i = i - 1
Example 20: Sort orders by amount (highest first) and print top 3
sorted_orders = sorted(orders, key=lambda order: order["amount"], reverse=True)
for order in sorted_orders[:3]:
print("Top Order:", order["id"], order["amount"])