IT243 Programming with Python

Programming with PythonUnit 39 min read

Control Flow: Loops, Conditions, and Decision-Making in Python

Unit 3 of Programming with Python covers conditional statements (if, elif, else), loops (for, while), and nested control structures, with real-world applications, algorithmic traces, and exam-focused problem-solving techniques.

TAKEAWAYS:

  • Conditional logic (if-elif-else) executes code blocks based on boolean tests, enabling branching decisions in programs.
  • Loops (for, while) automate repetitive tasks, reducing code redundancy and improving efficiency.
  • Nested control structures combine conditions and loops to handle complex logic hierarchically.
  • Loop control statements (break, continue, pass) modify loop execution flow dynamically.
  • Real-world applications include user authentication (e.g., eSewa login), order processing (e.g., Daraz delivery queues), and data validation (e.g., Ncell bill calculations).
  • Exam focus: Trace variable changes step-by-step in loops/conditions and identify edge cases (e.g., empty lists, zero values).

1. Conditional Statements: Branching Logic

Conditional statements allow programs to make decisions based on conditions. Python uses if, elif (else-if), and else for multi-way branching.

How It Works

  • Syntax:
    if condition1:
        # Code block 1
    elif condition2:
        # Code block 2
    else:
        # Default code block
    
  • Evaluation: Conditions are checked top-down. The first True condition executes its block; others are skipped. If all are False, else runs.

Example: Grade Calculator

Scenario: A student’s score determines their grade (A: ≥90, B: 80–89, etc.). Simulate this for a TU exam score of 85.

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Grade: {grade}")

Trace:

Step Condition Checked Result Action
1 score >= 90 False Skip if block
2 score >= 80 True Set grade = "B"
3 score >= 70 Not reached —
4 else Not reached —

Output: Grade: B

Real-World Tie-In

eSewa Login System:

  • Uses if-elif-else to validate user credentials:
    • if checks if the entered PIN matches the stored hash.
    • elif triggers if the account is locked after 3 failed attempts.
    • else redirects to password recovery.
  • Visual:
    flowchart TD
      A["User Enters PIN"] --> B{"Is PIN Correct?"}
      B -->|"Yes"| C["Grant Access"]
      B -->|"No"| D["Increment Attempts"]
      D --> E{"Attempts > 3?"}
      E -->|"Yes"| F["Lock Account"]
      E -->|"No"| B

2. Loop Structures: Repetition and Iteration

Loops execute code repeatedly until a condition is met. Python supports for (count-controlled) and while (condition-controlled) loops.

A. for Loop: Iterating Over Sequences

  • Syntax:
    for item in sequence:
        # Code block
    
  • Use Case: Process lists, strings, or ranges (e.g., range(start, stop, step)).

Example: Sum of First 5 Even Numbers

Scenario: Calculate the sum of even numbers from 2 to 10.

total = 0
for num in range(2, 11, 2):  # Start=2, Stop=11, Step=2
    total += num
print(f"Sum: {total}")

Trace:

Iteration num Value total Calculation
1 2 0 + 2 = 2
2 4 2 + 4 = 6
3 6 6 + 6 = 12
4 8 12 + 8 = 20
5 10 20 + 10 = 30

Output: Sum: 30

Real-World Tie-In

Daraz Order Processing:

  • Uses a for loop to iterate through a list of orders, updating stock levels and generating invoices.
  • Visual:

B. while Loop: Condition-Controlled Repetition

  • Syntax:
    while condition:
        # Code block
    
  • Use Case: Repeat until an unknown number of iterations (e.g., user input validation).

Example: ATM Withdrawal

Scenario: Simulate an ATM that dispenses ₹500 notes until the requested amount is met or the machine runs out.

amount = 2700
notes = 500
count = 0

while amount >= notes and notes != 0:
    amount -= notes
    count += 1
print(f"Notes dispensed: {count}")

Trace:

Iteration amount notes count Action
1 2700 500 0 2700 - 500 = 2200; count=1
2 2200 500 1 2200 - 500 = 1700; count=2
3 1700 500 2 1700 - 500 = 1200; count=3
4 1200 500 3 1200 - 500 = 700; count=4
5 700 500 4 Loop ends (700 < 500)

Output: Notes dispensed: 4 (₹2000 dispensed; ₹700 remains undispensed).

Real-World Tie-In

Ncell Top-Up Validation:

  • Uses a while loop to repeatedly prompt the user for a valid PIN until correct or max attempts reached.
  • Visual:
    flowchart TD
      A["Prompt for PIN"] --> B{"Is PIN Valid?"}
      B -->|"Yes"| C["Process Top-Up"]
      B -->|"No"| D["Decrement Attempts"]
      D --> E{"Attempts Left?"}
      E -->|"Yes"| A
      E -->|"No"| F["Block SIM"]

3. Loop Control Statements

Modify loop behavior dynamically.

Statement Purpose Example
break Exit loop immediately if amount <= 0: break
continue Skip current iteration if num % 2 != 0: continue
pass Placeholder (no action) else: pass

Example: Find First Even Number in a List

numbers = [1, 3, 5, 6, 7]
for num in numbers:
    if num % 2 == 0:
        print(f"First even: {num}")
        break

Output: First even: 6


4. Nested Control Structures

Combine loops/conditions to handle hierarchical logic.

Example: Multiplication Table with Validation

Scenario: Print a multiplication table for a user-input number (1–10), with validation.

num = int(input("Enter a number (1-10): "))
if 1 <= num <= 10:
    for i in range(1, 11):
        print(f"{num} x {i} = {num * i}")
else:
    print("Invalid input!")

Trace for num = 12:

Step Condition Check Action
1 1 <= 12 <= 10 False → else block

Output: Invalid input!

Real-World Tie-In

Khalti Transaction Fees:

  • Nested logic:
    1. if checks transaction amount.
    2. for loop iterates over fee tiers (e.g., 0–10,000: 2%, 10,001–50,000: 1.5%).
    3. else applies a flat fee for amounts >50,000.

5. Common Pitfalls and Best Practices

Issue Solution
Infinite loops Ensure while conditions can become False.
Off-by-one errors Use range(stop) for 0 to stop-1.
Unreachable code Place else after all elif blocks.
Redundant checks Use continue to skip invalid iterations.

Example: Off-by-One Error

Buggy Code:

for i in range(5):  # Prints 0 to 4
    print(i)

Fix for 1 to 5:

for i in range(1, 6):  # Start=1, Stop=6
    print(i)

In the Real World

  1. eSewa Bill Payment:

    • Idea Used: Nested if-elif-else to validate user input (e.g., account number format, sufficient balance).
    • How: Checks if the account exists (if), then verifies funds (elif), and finally processes payment (else).
  2. Pathao Driver Assignment:

    • Idea Used: while loop to assign the nearest available driver to a ride request.
    • How: Loop continues until a driver within 500m is found or all drivers are busy.
  3. NEPSE Stock Price Alerts:

    • Idea Used: for loop to scan a list of stocks and trigger alerts for price changes beyond thresholds.
    • Example:
      stocks = {"NTC": 120, "Ncell": 350, "NMB": 200}
      threshold = 10
      for stock, price in stocks.items():
          if abs(price - previous_price[stock]) > threshold:
              print(f"Alert: {stock} price changed!")
      

Exam Tip

  1. Trace Step-by-Step: For loop/condition questions, show a table of variable states (like the ATM example above). Examiners reward clarity.
  2. Edge Cases: Test with:
    • Empty lists/dictionaries.
    • Zero or negative numbers.
    • Boundary values (e.g., score = 90 in grade calculators).
  3. Pseudocode First: Write logic in plain English before coding. Example:

    "For each order in the cart, if the item’s stock is >0, deduct quantity and add to total; else, print ‘Out of stock.’"

  4. Avoid Magic Numbers: Use variables for constants (e.g., MAX_ATTEMPTS = 3 instead of hardcoding 3).
  5. Common Exam Questions:
    • Write a loop to reverse a string.
    • Calculate factorial using while.
    • Validate a password (length ≥8, contains a digit).
    • Simulate a traffic light system (use nested if for pedestrian crossing).

Visual Summary of Control Flow:

mindmap
  root((Control Flow))
    if-elif-else
      "Single condition: if"
      "Multiple conditions: elif"
      "Default case: else"
    for-loop
      "Iterate over sequences"
      "Range-based: range(start, stop, step)"
    while-loop
      "Condition-controlled"
      "Unknown iterations"
    loop-controls
      "break: Exit loop"
      "continue: Skip iteration"
      "pass: No-op"
    nested-structures
      "Loops inside conditions"
      "Conditions inside loops"

Based on the TU BITM syllabus for Programming with Python (IT243), unit 3.

Discussion

Loading…