Programming with PythonUnit 310 min read
Control Flow: Loops, Conditions & Decision-Making in Python
Unit 3 of Programming with Python covers conditional statements (if, elif, else), loops (for, while), and control flow techniques like break, continue, and pass, with real-world applications, algorithmic traces, and exam-focused problem-solving strategies.
TAKEAWAYS:
- Control flow determines how and when code executes, using conditions and loops to handle repetition and branching.
if-elif-elseevaluates conditions sequentially;forloops iterate over sequences, whilewhileloops run until a condition is false.breakexits a loop early,continueskips to the next iteration, andpassacts as a placeholder.- Nested loops and conditions create complex logic but must be optimized to avoid inefficiency (e.g., O(n²) vs. O(n)).
- Real-world systems (e.g., eSewa’s payment validation, Pathao’s ride-matching) rely on control flow for decision-making.
- Debugging loops requires tracing variables step-by-step to identify infinite loops or logical errors.
1. Conditional Statements: if, elif, else
Conditional statements execute code blocks based on boolean evaluations. They are the backbone of decision-making in programs.
How It Works
if: Checks a condition. If true, executes the indented block.elif(else-if): Checks additional conditions if previous ones fail.else: Executes if all prior conditions are false.- Syntax:
if condition1: # code block 1 elif condition2: # code block 2 else: # default code block
Worked Example: eSewa Payment Validation
Suppose eSewa checks if a user’s balance is sufficient before processing a payment:
balance = 500
payment_amount = 600
if balance >= payment_amount:
print("Payment successful!")
elif balance > 0:
print(f"Insufficient balance. Top up by {payment_amount - balance}.")
else:
print("No balance available.")
Output:
Insufficient balance. Top up by 100.
Visual: Condition Evaluation Flow
flowchart TD
A["Start"] --> B["Check: balance >= payment?"]
B -->|"Yes"| C["Process Payment"]
B -->|"No"| D["Check: balance > 0?"]
D -->|"Yes"| E["Show Top-up Amount"]
D -->|"No"| F["Show No Balance"]Key Rules
- Use
eliffor multiple conditions (avoid chainingifstatements). - Avoid deep nesting (more than 3 levels) to improve readability.
- Short-circuit evaluation: Python stops checking further conditions once one is true (e.g.,
if A and B: ...skipsBifAis false).
2. Loop Structures: for and while
Loops repeat code blocks until a condition is met. They are essential for processing collections or repeating tasks.
A. for Loop: Iterating Over Sequences
- Used to traverse lists, tuples, strings, dictionaries, or ranges.
- Syntax:
for item in sequence: # code block
Worked Example: Pathao Ride-Matching
Pathao matches riders to drivers based on location. Simulate checking 5 nearby drivers:
drivers = ["Driver1", "Driver2", "Driver3", "Driver4", "Driver5"]
matched = False
for driver in drivers:
if driver == "Driver3": # Assume Driver3 is available
print(f"Matched with {driver}!")
matched = True
break
if not matched:
print("No drivers available.")
Output:
Matched with Driver3!
Visual: for Loop Execution
flowchart TD
A["Start"] --> B["Initialize: drivers = ['D1', 'D2', 'D3']"]
B --> C["for driver in drivers:"]
C --> D["Check: driver == 'D3'?"]
D -->|"Yes"| E["Print Match"]
D -->|"No"| F["Next Iteration"]
F --> CB. while Loop: Conditional Repetition
- Runs as long as a condition is true.
- Syntax:
while condition: # code block
Worked Example: NTC Call Retry Logic
NTC’s IVR system retries a call until it connects (max 3 attempts):
attempts = 0
max_attempts = 3
while attempts < max_attempts:
print(f"Attempt {attempts + 1}: Calling...")
# Simulate connection (random success)
if random.choice([True, False]):
print("Connected!")
break
attempts += 1
else:
print("Max attempts reached. Call failed.")
Output (possible):
Attempt 1: Calling...
Attempt 2: Calling...
Connected!
Visual: while Loop with break
flowchart TD
A["Start"] --> B["Initialize: attempts = 0"]
B --> C["while attempts < 3:"]
C --> D["Call NTC"]
D -->|"Success"| E["Print Connected\nBreak"]
D -->|"Fail"| F["attempts += 1"]
F --> C
C --> G["Max Attempts\nExit"]Comparison: for vs. while
| Feature | for Loop |
while Loop |
|---|---|---|
| Use Case | Known iterations (lists, ranges) | Unknown iterations (conditions) |
| Termination | Automatically (sequence length) | Manual (break or condition) |
| Example | for i in range(5): |
while user_input != "quit": |
| Risk | Less prone to infinite loops | Can loop infinitely if misused |
3. Loop Control Statements
These modify loop behavior dynamically.
A. break
- Exits the loop immediately.
- Example: Stop searching once a match is found (as in Pathao’s driver matching above).
B. continue
- Skips the current iteration and moves to the next.
- Example: Skip even numbers in a list:
Output:numbers = [1, 2, 3, 4, 5] for num in numbers: if num % 2 == 0: continue print(num)1 3 5
C. pass
- A placeholder that does nothing. Used for syntax completeness.
- Example: Stub for future code:
if user_is_admin: pass # To be implemented later
Visual: continue in Action
flowchart TD
A["Start"] --> B["for num in [1,2,3,4]:"]
B --> C["Check: num % 2 == 0?"]
C -->|"Yes"| D["continue\nSkip"]
C -->|"No"| E["Print num"]
D --> B4. Nested Loops and Efficiency
Nested loops combine to solve multi-dimensional problems but can degrade performance.
Example: Daraz Order Processing
Simulate checking all items in a cart for stock availability:
cart = [("Laptop", 2), ("Mouse", 5), ("Keyboard", 0)]
out_of_stock = []
for item, quantity in cart:
if quantity <= 0:
out_of_stock.append(item)
continue # Skip further checks for this item
print(f"{item}: Available")
Output:
Mouse: Available
Laptop: Available
Performance Impact
- Time Complexity:
- Single loop: O(n)
- Nested loops: O(n²) (e.g., comparing every item to every other item).
- Optimization: Use dictionaries for O(1) lookups instead of nested loops.
Visual: Nested Loop Complexity
flowchart TD
A["Outer Loop\nItems"] --> B["Inner Loop\nCheck Stock"]
B --> C["If Out of Stock:\nAdd to List"]
B --> D["Else:\nPrint Available"]
C --> A5. Infinite Loops and How to Avoid Them
Infinite loops occur when the termination condition is never met.
Common Causes
- Missing update in
whilecondition:x = 0 while x < 5: # x never increments print(x) - Logical error in condition:
while user_input != "quit": # But user_input is never set! user_input = input("Enter: ")
How to Fix
- Always update loop variables (e.g.,
x += 1). - Use
breakfor early exits. - Test edge cases (e.g., empty lists, zero values).
Visual: Infinite Loop Trap
flowchart TD
A["Start"] --> B["while x < 5:"]
B --> C["Print x"]
C --> BIn the Real World
eSewa’s Payment Flow
- Idea Used: Nested
if-elif-elsefor multi-step validation (balance, PIN, transaction limits). - How: Checks user balance → PIN → bank connectivity → finalizes payment.
- Code Snippet:
if balance >= amount: if pin == user_pin: if bank_connectivity: deduct_balance(amount) print("Paid!")
- Idea Used: Nested
Pathao’s Ride-Matching Algorithm
- Idea Used:
forloop withbreakto find the nearest available driver. - How: Iterates through nearby drivers until it finds one with
status == "available".
- Idea Used:
NTC’s IVR System
- Idea Used:
whileloop withbreakfor retry logic. - How: Calls a number up to 3 times before failing (as shown in the earlier example).
- Idea Used:
Daraz’s Inventory Check
- Idea Used: Nested loops (cart items × stock database).
- Optimization: Replaced with a dictionary lookup for O(1) stock checks.
Bank Loan Interest Calculation
- Idea Used:
forloop to compute monthly installments. - Example: A 5-year loan with monthly payments:
principal = 100000 rate = 0.05 for month in range(60): interest = principal * rate / 12 payment = (principal + interest) / remaining_terms principal -= payment
- Idea Used:
Exam Tip
Trace Step-by-Step: For loop questions, show the state after each iteration (e.g., variable values in a table).
- Example:
Iteration inumbers[i]Condition Check 1 0 10 i < 3→ True2 1 20 i < 3→ True
- Example:
Watch for Off-by-One Errors:
range(5)generates0, 1, 2, 3, 4(not 5).while i <= 5may miss the last element.
Pseudocode is Your Friend:
- Write logic in plain English before coding. Example:
FOR each driver IN nearby_drivers: IF driver.available AND driver.distance < 5km: MATCH driver BREAK
- Write logic in plain English before coding. Example:
Common Pitfalls:
- Forgetting to indent code blocks (Python is strict!).
- Using
==instead ofisforNonechecks. - Infinite loops in
whilequestions (always check termination).
Practical Questions:
- Expect problems like:
- "Write a loop to find the second largest number in a list."
- "Simulate a traffic light system using nested loops."
- "Debug the following code with an infinite loop."
- Expect problems like:
Final Note: Control flow is about logic, not just syntax. Practice tracing loops on paper—it’s the fastest way to master this unit!
Based on the TU BIM syllabus for Programming with Python (IT243), unit 3.
Discussion
Loading…