Lab 06: Control Flow — Conditionals & Loops

🎯 Objective

Master Python's decision-making structures (if/elif/else) and loops (for, while) — the logic that drives every real program.

📚 Background

Control flow determines the order in which code executes. Without it, programs would just run top-to-bottom and stop. Conditionals let code make decisions; loops let code repeat. Python's syntax is cleaner than most languages — no curly braces, just indentation. Python also has unique features like for/else, while/else, and the ternary expression.

⏱️ Estimated Time

35 minutes

📋 Prerequisites

  • Lab 5: Dictionaries

🛠️ Tools Used

  • Python 3.12

🔬 Lab Instructions

Step 1: Basic if/elif/else

📸 Verified Output:

💡 Python evaluates elif chains top-to-bottom and stops at the first True condition. Always put more specific conditions first, general conditions last.

Step 2: Ternary Expression (One-Line If)

📸 Verified Output:

Step 3: for Loop Fundamentals

📸 Verified Output:

Step 4: enumerate() and zip()

📸 Verified Output:

💡 enumerate() is preferred over for i in range(len(list)) — it's more Pythonic and less error-prone. zip() stops at the shortest sequence.

Step 5: while Loop

📸 Verified Output:

Step 6: break, continue, pass

📸 Verified Output:

Step 7: Nested Loops

📸 Verified Output:

Step 8: Comprehension with Conditions

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Infinite while loop: Always ensure the loop condition eventually becomes False or has a break.

  2. Off-by-one in range(): range(n) gives 0..n-1; range(1, n+1) gives 1..n.

  3. Modifying a list while iterating: Causes skipped elements — iterate a copy: for item in list(my_list).

  4. Using = instead of == in conditions: if x = 5 is a SyntaxError in Python (assignment, not comparison).

  5. Deep nesting: More than 3 levels of nesting is hard to read — use functions to break it up.

📝 Summary

  • if/elif/else chains: evaluated top-to-bottom, first match wins

  • Ternary: value_if_true if condition else value_if_false

  • for item in iterable — Python's primary loop; works on any iterable

  • enumerate(iterable, start=0) gives index+value pairs

  • zip(a, b) loops two iterables together

  • break exits the loop; continue skips to next iteration; pass does nothing

  • Prefer comprehensions for simple transformations; use regular loops for complex logic

🔗 Further Reading

Last updated