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, andelseto handle multiple scenarios. - Iteration: Using
for(specifically "for-each" in Python) andwhile. - Match-Case: Using Python 3.10's structural pattern matching for complex conditional branching.
π Complexity & Performance
- List Comprehensions: Faster than traditional
forloops because they are executed at C-speed inside the interpreter. whilevsfor:forloops in Python are optimized for iterating over iterables.whileloops are better for conditions that aren't tied to a specific collection size.- Boolean Short-circuiting: Python's
andandoroperators 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 Standarddef 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
- Mutable Default Arguments: Never use mutable objects (like lists) as default arguments in functions called within loops. They persist across calls.
- The "For-Else" Confusion: Many candidates think
elseruns if the loop breaks. Correct Answer: It runs if the loop doesn't break. - Indentation Errors: In a whiteboard interview, failing to maintain consistent indentation is often looked down upon more than logic errors.
isvs==: Use==for value equality andisfor identity (checking if two names point to the same object).