Python – Control Flow & Iteration
Programs do not always execute every line in the same order. Sometimes, we must make decisions. Sometimes, we must repeat a task. Sometimes, we must stop a loop when a condition is satisfied.
Python provides control flow statements to manage these execution paths. They help us build programs that respond to data and user actions.
- How Python makes decisions using
if,elif, andelse. - How to match values using
matchandcase. - How to repeat operations using
forandwhile. - How
break,continue, andpasschange execution. - How loop nesting and loop
elsework. - How to apply these concepts in a practical order-processing example.
1. What Is Control Flow in Python?
Control flow means the order in which program statements execute. By default, Python runs statements from top to bottom. Control flow statements change this order based on conditions or repetition.
Consider an online order system. It must check payment status before confirming an order. It must also process every item in the customer's cart. These tasks need decisions and repetition.
| Control flow type | Purpose | Python statements |
|---|---|---|
| Decision making | Choose a path based on a condition | if, elif, else, match |
| Iteration | Repeat a block of code | for, while |
| Loop control | Change or stop loop execution | break, continue, pass |
2. Decision Making Using if, elif and else
The if statement executes a block when its condition is true. The elif statement checks another condition. The else block handles the remaining case.
Basic if statement
Let's check whether an order has been paid.
Example 1: Checking payment status
payment_status = "PAID"
if payment_status == "PAID":
print("Order confirmed")
Expected output
Order confirmed
Python evaluates the condition after if. The indented statement runs only when the condition is true.
Using if and else
We can provide an alternative path when the condition is false.
Example 2: Payment decision
payment_status = "PENDING"
if payment_status == "PAID":
print("Order confirmed")
else:
print("Payment is not completed")
Expected output
Payment is not completed
Using if, elif and else
Use elif when multiple conditions need checking. Python checks them from top to bottom. The first true condition gets executed.
Example 3: Order status classification
order_amount = 7500
if order_amount >= 10000:
print("Premium order")
elif order_amount >= 5000:
print("Standard order")
elif order_amount > 0:
print("Small order")
else:
print("Invalid order amount")
Expected output
Standard order
Nested if statements
A nested if is an if statement inside another if statement. Use it when one decision depends on another decision.
Example 4: Order confirmation checks
payment_status = "PAID"
stock_available = True
if payment_status == "PAID":
if stock_available:
print("Order confirmed")
else:
print("Product is out of stock")
else:
print("Complete payment first")
Expected output
Order confirmed
3. Combining Conditions with Logical Operators
Sometimes, one decision depends on more than one condition. Python provides logical operators for this purpose.
| Operator | Meaning | Result |
|---|---|---|
and |
Both conditions must be true | True only when both are true |
or |
At least one condition must be true | True when either is true |
not |
Reverses a Boolean result | True becomes False and vice versa |
Example 5: Checking order eligibility
payment_status = "PAID"
stock_available = True
is_blocked = False
if payment_status == "PAID" and stock_available and not is_blocked:
print("Order can be processed")
else:
print("Order cannot be processed")
Expected output
Order can be processed
Python also supports comparison chaining. It makes range checks easier to read.
Example 6: Chained comparison
age = 25
if 18 <= age <= 60:
print("Eligible")
else:
print("Not eligible")
Expected output
Eligible
4. Pattern Matching with match and case
Python 3.10 introduced structural pattern matching through match and case. It provides a clear way to handle multiple possible patterns or values.
It is useful when one variable can represent several known options.
Example 7: Handling order actions
action = "SHIP"
match action:
case "CREATE":
print("Creating order")
case "SHIP":
print("Shipping order")
case "CANCEL":
print("Cancelling order")
case _:
print("Unknown action")
Expected output
Shipping order
The underscore pattern acts as a catch-all case. It handles values that do not match earlier cases.
match statement requires Python 3.10 or later. Use if and elif when supporting older Python versions.5. What Is Iteration in Python?
Iteration means repeating a block of code. It avoids writing the same statements many times. Python provides two main loop statements: for and while.
For example, an order may contain five products. We can use a loop to process each product instead of writing five separate statements.
How a Python loop executes
A loop checks its condition, runs the body when true, and repeats. It exits when the condition becomes false or a control statement stops it.
6. for Loop – Iterating Over a Sequence
A for loop processes items from an iterable. An iterable is an object that can provide its items one by one. Lists, tuples, strings, dictionaries, and ranges are common examples.
Loop through a list
Example 8: Processing order items
products = ["Laptop", "Mouse", "Keyboard"]
for product in products:
print("Processing:", product)
Expected output
Processing: Laptop Processing: Mouse Processing: Keyboard
Python takes one item from the list during each iteration. The variable product refers to the current item.
Using range()
The range() function generates a sequence of integers. It is commonly used when we need to repeat an operation a known number of times.
Example 9: Repeating an operation
for number in range(1, 6):
print(number)
Expected output
1 2 3 4 5
range(1, 6) starts at 1 and stops before 6. The stop value is exclusive.
Understanding range() parameters
| Syntax | Generated values | Explanation |
|---|---|---|
range(5) |
0, 1, 2, 3, 4 | Starts at zero |
range(1, 5) |
1, 2, 3, 4 | Start and stop values |
range(1, 10, 2) |
1, 3, 5, 7, 9 | Uses a step of two |
range(5, 0, -1) |
5, 4, 3, 2, 1 | Counts backwards |
Loop through a dictionary
A dictionary stores key-value pairs. Use items() when both values are required.
Example 10: Reading product quantities
cart = {
"Laptop": 1,
"Mouse": 2,
"Keyboard": 1
}
for product, quantity in cart.items():
print(product, ":", quantity)
Expected output
Laptop : 1 Mouse : 2 Keyboard : 1
7. while Loop – Repeating While a Condition Is True
A while loop repeats as long as its condition remains true. It is useful when the number of iterations is not known in advance.
For example, we may retry a payment until it succeeds or reaches a retry limit.
Example 11: Payment retry simulation
attempt = 1
maximum_attempts = 3
while attempt <= maximum_attempts:
print("Payment attempt:", attempt)
attempt += 1
print("Retry limit completed")
Expected output
Payment attempt: 1 Payment attempt: 2 Payment attempt: 3 Retry limit completed
How the while loop works
8. break – Stop a Loop Immediately
The break statement terminates the nearest enclosing loop. Python continues execution from the first statement after that loop.
Example 12: Finding a product
products = ["Laptop", "Mouse", "Keyboard", "Monitor"]
for product in products:
if product == "Keyboard":
print("Product found")
break
print("Checking:", product)
Expected output
Checking: Laptop Checking: Mouse Product found
After finding the keyboard, Python exits the loop. It does not check the monitor.
9. continue – Skip the Current Iteration
The continue statement skips the remaining statements in the current iteration. The loop then moves to its next iteration.
Example 13: Skipping unavailable products
stock = [5, 0, 3, 0, 8]
for quantity in stock:
if quantity == 0:
continue
print("Available quantity:", quantity)
Expected output
Available quantity: 5 Available quantity: 3 Available quantity: 8
Zero-stock entries are skipped. The loop continues processing the remaining values.
10. pass – A Statement That Does Nothing
The pass statement is a placeholder. Python executes it without performing an operation. It is useful when a block is required but its implementation is not ready.
Example 14: Placeholder for future implementation
payment_status = "PENDING"
if payment_status == "PAID":
print("Process order")
else:
pass
print("Application continues")
Expected output
Application continues
Unlike break and continue, pass does not change loop execution.
11. for Loop vs while Loop
| Comparison | for loop | while loop |
|---|---|---|
| Typical use | Iterate over items | Repeat while a condition holds |
| Iteration count | Often known from the iterable | May not be known in advance |
| Condition handling | Managed by the iterable | Explicit Boolean condition |
| Common risk | Incorrect collection handling | Infinite loop |
| Example | Read every cart item | Retry a payment operation |
Choose a for loop when processing an iterable. Choose a while loop when repetition depends on a condition.
12. Nested Loops
A nested loop is a loop inside another loop. The inner loop completes its iterations for every iteration of the outer loop.
This is useful for processing rows and columns, combinations, or grouped data.
Example 15: Printing an order summary grid
for row in range(1, 4):
for column in range(1, 3):
print(f"Row {row}, Item {column}")
Expected output
Row 1, Item 1 Row 1, Item 2 Row 2, Item 1 Row 2, Item 2 Row 3, Item 1 Row 3, Item 2
The outer loop runs three times. The inner loop runs twice for each outer iteration. Therefore, the body executes six times.
13. The else Clause with Loops
Python allows an else block after a for or while loop. This block executes when the loop finishes normally. It does not execute when the loop ends through break.
Example 16: Searching for an order
order_ids = [101, 102, 103, 104]
target = 105
for order_id in order_ids:
if order_id == target:
print("Order found")
break
else:
print("Order not found")
Expected output
Order not found
This pattern is useful for search operations. The else block confirms that the loop completed without finding a match.
14. Practical Example – Processing an Order Cart
Let's combine conditions and iteration in one practical example. We will calculate the total for available products. We will skip unavailable items and identify whether the order qualifies for free delivery.
Example 17: Complete order processing program
cart = [
{"name": "Laptop", "price": 55000, "quantity": 1},
{"name": "Mouse", "price": 700, "quantity": 2},
{"name": "Keyboard", "price": 1500, "quantity": 0},
{"name": "Monitor", "price": 12000, "quantity": 1}
]
total_amount = 0
for item in cart:
if item["quantity"] <= 0:
print(item["name"], "- unavailable")
continue
item_total = item["price"] * item["quantity"]
total_amount += item_total
print(item["name"], "-", item_total)
if total_amount >= 50000:
delivery_charge = 0
print("Free delivery applied")
else:
delivery_charge = 100
final_amount = total_amount + delivery_charge
print("Subtotal:", total_amount)
print("Delivery:", delivery_charge)
print("Final amount:", final_amount)
Expected output
Laptop - 55000 Mouse - 1400 Keyboard - unavailable Monitor - 12000 Free delivery applied Subtotal: 68400 Delivery: 0 Final amount: 68400
Understanding the execution
continue.This example combines for, if, continue, and arithmetic operations. These patterns appear frequently in business applications.
15. Common Mistakes and Best Practices
Forgetting indentation
Python uses indentation to identify code blocks. Incorrect indentation can cause an IndentationError or change the intended program structure.
Correct indentation
if total_amount > 0:
print("Valid order")
print("Continue processing")
Using assignment instead of comparison
Use == to compare values. A single = assigns a value to a variable.
Creating an infinite while loop
Make sure the loop condition can eventually become false. Update the relevant variable or provide a controlled exit.
Modifying a collection while iterating over it
Changing a list during iteration can cause items to be skipped or produce confusing results. When filtering, create a new list or iterate over a copy when appropriate.
Choosing the wrong loop
Avoid manually managing an index when direct iteration is enough. Prefer readable code over unnecessary loop complexity.
16. Hands-On Practice
Read a number and identify whether it is positive, negative, or zero.
Hint: Use if, elif, and else.
Print all even numbers from 1 to 20 using a loop.
Hint: Use range() and the remainder operator.
Accept a list of product prices. Calculate the total using a for loop.
Expected result: Print the sum of all product prices.
Search for an order ID in a list. Stop the search when it is found.
Hint: Use break and loop else.
Allow a maximum of three payment attempts. Stop immediately when payment succeeds.
Hint: Combine while, if, and break.
17. Python Control Flow – Interview Questions
Answer: if starts a conditional decision. elif checks another condition when earlier conditions were false.
Answer: A for loop iterates over an iterable. A while loop repeats while its condition remains true.
Answer: break exits the nearest loop. continue skips the current iteration and proceeds to the next one.
Answer: pass is a placeholder statement. It performs no operation but allows a syntactically required block to remain empty.
Answer: The loop's else block executes when the loop completes normally. It is skipped when the loop terminates through break.
18. Conclusion
Control flow gives Python programs the ability to make decisions. Iteration helps programs repeat tasks without duplicate code. Together, these concepts form the foundation of practical programming.
Start with simple conditions and loops. Then practise combining them in realistic programs. Focus on indentation, readable conditions, correct loop termination, and clear variable names.
Once these concepts become familiar, you can use them confidently in functions, collections, file processing, APIs, and larger Python applications.
Official Documentation
- Python Tutorial – More Control Flow Tools
- Python Language Reference – Compound Statements
- Python Documentation – range()
Upgradix by Shrash Studio – Learn Technology. Build Your Future.