Core Module
12 min forge

Python Control Flow

Master the logic of Python. Conditionals, iterative loops, and the unique for-else pattern.

Python Control Flow

πŸ›‘οΈ What is Control Flow?

Control flow is the structure that governs the execution order of code based on logic and boolean conditions. Python relies on indentation rather than braces to define code blocks, making control flow highly readable.

⏰ When to Use

  • Branching: Using if, elif, and else to handle multiple scenarios.
  • Iteration: Using for (specifically "for-each" in Python) and while.
  • Match-Case: Using Python 3.10's structural pattern matching for complex conditional branching.

πŸ“Š Complexity & Performance

  • List Comprehensions: Faster than traditional for loops because they are executed at C-speed inside the interpreter.
  • while vs for: for loops in Python are optimized for iterating over iterables. while loops are better for conditions that aren't tied to a specific collection size.
  • Boolean Short-circuiting: Python's and and or operators evaluate lazily, which can be leveraged for performance (e.g., if expensive_check() or quick_check(): is inefficient; swap them).

πŸ’» Code Example: The Advanced For-Else

python Standard
def find_prime(n): # 1. The structural pattern matching (Python 3.10+) match n: case 1: return False case 2: return True # 2. Loop with 'else' clause # The 'else' block executes ONLY if the loop completes without a 'break' for i in range(2, int(n**0.5) + 1): if n % i == 0: print(f"{n} is divisible by {i}") break else: print(f"{n} is a prime number!") return True return False # 3. List Comprehension (Implicit Loop) squares = [x**2 for x in range(10) if x % 2 == 0]

⚠️ Interview Pitfalls

  1. Mutable Default Arguments: Never use mutable objects (like lists) as default arguments in functions called within loops. They persist across calls.
  2. The "For-Else" Confusion: Many candidates think else runs if the loop breaks. Correct Answer: It runs if the loop doesn't break.
  3. Indentation Errors: In a whiteboard interview, failing to maintain consistent indentation is often looked down upon more than logic errors.
  4. is vs ==: Use == for value equality and is for identity (checking if two names point to the same object).