DEV Community

Cover image for Python Notes #3 – Control Flow
Elvin Seyidov
Elvin Seyidov

Posted on • Edited on • Originally published at elvinseyidov.com

Python Notes #3 – Control Flow

Conditional Statements

if, elif, else
Python uses if, elif, and else for decision-making. Conditions are evaluated top-down, and the first true branch executes. Python treats 0, None, [], {}, "", and False as falsy — everything else is truthy.

✅ Avoid Deep Nesting

# Instead of: if user: if user.is_active: if user.is_admin: do_admin_stuff() # Prefer: if not user or not user.is_active or not user.is_admin: return do_admin_stuff() 
Enter fullscreen mode Exit fullscreen mode

✅ Use Ternary Expressions for Simple Conditions

status = "active" if user.is_active else "inactive" 
Enter fullscreen mode Exit fullscreen mode

✅ Leverage Truthy/Falsy Evaluations

if items: # Instead of if len(items) > 0 process(items) 
Enter fullscreen mode Exit fullscreen mode

✅ Use in and not in for Clean Membership Checks

if role in {"admin", "moderator"}: grant_access() 
Enter fullscreen mode Exit fullscreen mode

Looping Constructs

Python offers for and while loops, both supporting an optional else block that runs only if the loop is not exited via break. Useful for search-style logic.

✅ for Loops with range, enumerate, zip

# range for i in range(1, 6): print(i) # enumerate for i, item in enumerate(items, start=1): print(f"{i}: {item}") # zip for name, score in zip(names, scores): print(f"{name}: {score}") 
Enter fullscreen mode Exit fullscreen mode

✅ while Loop + else

i = 0 while i < 5: if should_stop(i): break i += 1 else: print("Completed without break") 
Enter fullscreen mode Exit fullscreen mode

✅ break, continue, pass

for x in data: if x == target: break # Exit loop early if x < 0: continue # Skip this iteration process(x) def todo(): pass # Placeholder for future code 
Enter fullscreen mode Exit fullscreen mode

Comprehensions with Conditions

Python comprehensions provide a clean and expressive way to build sequences. Conditions can be added inline to filter or transform items.

✅ List Comprehension with if

# Filter even numbers evens = [x for x in nums if x % 2 == 0] 
Enter fullscreen mode Exit fullscreen mode

✅ List Comprehension with if-else

# Tag even/odd labels = ["even" if x % 2 == 0 else "odd" for x in nums] 
Enter fullscreen mode Exit fullscreen mode

✅ Dict Comprehension with Condition

# Squared values for positives only squared = {x: x**2 for x in nums if x > 0} 
Enter fullscreen mode Exit fullscreen mode

✅ Set Comprehension with Condition

# Unique lowercase characters chars = {c.lower() for c in text if c.isalpha()} 
Enter fullscreen mode Exit fullscreen mode

Pattern Matching (match-case)

Introduced in Python 3.10, match-case provides cleaner alternatives to long if-elif chains. It supports structural pattern matching, guards, and destructuring.

✅ Basic Matching

match command: case "start": run() case "stop": shutdown() case _: print("Unknown command") 
Enter fullscreen mode Exit fullscreen mode

✅ Match with Guards (Conditions)

match user: case {"role": "admin"} if user["active"]: grant_access() case _: deny_access() 
Enter fullscreen mode Exit fullscreen mode

✅ Destructuring Tuples / Sequences

match point: case (0, 0): print("Origin") case (x, 0): print(f"X-axis at {x}") case (x, y): print(f"Point at ({x}, {y})") 
Enter fullscreen mode Exit fullscreen mode

✅ Matching Class Attributes

class User: def __init__(self, name, active): self.name = name; self.active = active match u: case User(name="admin", active=True): print("Admin is active") 
Enter fullscreen mode Exit fullscreen mode

Best Practices & Tips

✅ Use loop-else for Search Logic
The else clause on loops executes only if the loop wasn't broken. Ideal for search patterns.

for user in users: if user.is_admin: notify(user) break else: log("No admin found") 
Enter fullscreen mode Exit fullscreen mode

✅ Avoid Deep Nesting
Flatten logic by returning early or using guard clauses.

# ❌ Deeply nested if user: if user.active: if user.role == "admin": grant_access() # ✅ Cleaner if not user or not user.active or user.role != "admin": return grant_access() 
Enter fullscreen mode Exit fullscreen mode

✅ Use Pythonic Alternatives

  • Replace flag variables with early exits

  • Use comprehensions instead of loop-based filtering

  • Use any(), all(), filter(), map() where appropriate

# Example: Check if any item is negative if any(x < 0 for x in nums): warn() # Efficient – any() stops early when it finds the first True. # Filter positive numbers positives = [x for x in nums if x > 0] # Faster – List comprehensions execute in C under the hood. # all() – Checks if All Conditions are True if all(x > 0 for x in nums): print("All numbers are positive") # filter() – Functional Filtering positives = list(filter(lambda x: x > 0, nums)) #Returns a filtered iterator, saving memory for large datasets. # map() – Apply a Function to Each Element squared = list(map(lambda x: x**2, nums)) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)