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()

✅ Use Ternary Expressions for Simple Conditions

status = "active" if user.is_active else "inactive"

✅ Leverage Truthy/Falsy Evaluations

if items:  # Instead of if len(items) > 0
    process(items)

✅ Use in and not in for Clean Membership Checks

if role in {"admin", "moderator"}:
    grant_access()

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}")

✅ while Loop + else

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

✅ 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

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]

✅ List Comprehension with if-else

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

✅ Dict Comprehension with Condition

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

✅ Set Comprehension with Condition

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

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")

✅ Match with Guards (Conditions)

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

✅ 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})")

✅ 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")

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")

✅ 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()

✅ 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))