Fatskills
Practice. Master. Repeat.
Study Guide: TECH **Python for Data Science: Control Flow – Zero-Fluff Study Guide**
Source: https://www.fatskills.com/data-science/chapter/tech-python-for-data-science-control-flow-zero-fluff-study-guide

TECH **Python for Data Science: Control Flow – Zero-Fluff Study Guide**

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~7 min read

Python for Data Science: Control Flow – Zero-Fluff Study Guide

(if-elif-else, for/while loops, comprehensions)


1. What This Is & Why It Matters

Control flow is the skeleton of your data science scripts. Without it, your code runs top-to-bottom like a robot reading a shopping list—no decisions, no repetition, no efficiency.

Real-world scenario:
You’re cleaning a 10GB CSV of customer transactions. Some rows have missing values, others have outliers (e.g., a $1M purchase in a "Groceries" category). You need to: - Skip rows with missing customer_id (if-else).
- Flag transactions over $10K for fraud review (elif).
- Iterate through each row to compute rolling averages (for loop).
- Stop early if the file is corrupted (while loop with break).
- Build a new DataFrame with only valid rows (list comprehension).

What breaks if you ignore this?
- Your script crashes on the first missing value (no error handling).
- You process the entire 10GB file even if the first 100 rows are garbage (no early exit).
- Your code becomes a 500-line mess of nested if statements (no comprehensions).
- You waste hours waiting for slow loops (no vectorized alternatives).

Superpower it gives you:
- Automate decisions (e.g., "If this column is empty, fill it with the median").
- Process data in bulk (e.g., "For each column, normalize values between 0 and 1").
- Write clean, maintainable code (e.g., "Use a comprehension to filter outliers in one line").


2. Core Concepts & Components


1. if-elif-else (Conditional Logic)

  • Definition: Execute code blocks based on boolean conditions.
  • Production insight: Always handle edge cases (e.g., NaN, None, empty strings). A single unhandled None can crash a production pipeline.

2. for Loops (Iteration)

  • Definition: Repeat a block of code for each item in a sequence (list, dict, DataFrame rows).
  • Production insight: Avoid loops on large DataFrames—use vectorized operations (df.apply()) or numpy for speed.

3. while Loops (Conditional Iteration)

  • Definition: Repeat a block while a condition is True.
  • Production insight: Always include a safety counter (e.g., max_iterations = 1000) to prevent infinite loops in production.

4. List/Dict/Set Comprehensions (One-Liners)

  • Definition: Concise syntax to create new sequences from existing ones.
  • Production insight: Comprehensions are faster than loops (Python optimizes them) and cleaner for simple transformations.

5. break and continue (Loop Control)

  • Definition:
  • break: Exit the loop immediately.
  • continue: Skip to the next iteration.
  • Production insight: Use break to exit early (e.g., "Stop processing if the file is corrupted"). Use continue to skip bad data (e.g., "Ignore rows with missing values").

6. try-except (Error Handling)

  • Definition: Catch and handle exceptions (e.g., KeyError, ValueError).
  • Production insight: Log errors before raising them—debugging is 10x harder without logs.

7. enumerate() (Index Tracking)

  • Definition: Loop over a sequence while tracking the index.
  • Production insight: Useful for modifying DataFrame rows by position (e.g., "Update the 3rd column if the 5th column is empty").

8. zip() (Parallel Iteration)

  • Definition: Loop over multiple sequences simultaneously.
  • Production insight: Merge two DataFrames column-wise (e.g., "Combine df1['id'] and df2['name'] into a new dict").


3. Step-by-Step Hands-On: Cleaning a Messy Dataset

Task: You’re given a CSV of e-commerce transactions with missing values, duplicates, and outliers. Clean it using control flow.

Prerequisites

  • Python 3.8+ installed.
  • pandas and numpy installed (pip install pandas numpy).
  • A sample CSV (transactions.csv) with columns: order_id, customer_id, amount, category.

Step 1: Load the Data

import pandas as pd

df = pd.read_csv("transactions.csv")
print(f"Original shape: {df.shape}")

Step 2: Handle Missing Values (if-elif-else)

# Fill missing 'customer_id' with 'UNKNOWN'
df["customer_id"] = df["customer_id"].fillna("UNKNOWN")

# Drop rows where 'amount' is missing (no way to impute)
df = df.dropna(subset=["amount"])

Step 3: Flag Outliers (for loop + if-else)

outliers = []
for idx, row in df.iterrows():
if row["amount"] > 10000 and row["category"] != "Electronics":
outliers.append(row["order_id"]) print(f"Flagged {len(outliers)} outliers for review.")

Step 4: Remove Duplicates (while loop + break)

# Remove duplicates until none are left
while True:
initial_count = len(df)
df = df.drop_duplicates()
if len(df) == initial_count: # No more duplicates
break print(f"Removed {initial_count - len(df)} duplicates.")

Step 5: Normalize Categories (list comprehension)

# Standardize category names (e.g., "groceries" -> "Groceries")
df["category"] = [cat.strip().title() for cat in df["category"]]

Step 6: Save Cleaned Data

df.to_csv("transactions_cleaned.csv", index=False)
print("Cleaned data saved to 'transactions_cleaned.csv'.")

Expected Output

Original shape: (10000, 4)
Flagged 42 outliers for review.
Removed 123 duplicates.
Cleaned data saved to 'transactions_cleaned.csv'.


4. ? Production-Ready Best Practices


Performance

  • Avoid loops on DataFrames: Use df.apply() or numpy vectorization.
    ```python # Bad (slow) for idx, row in df.iterrows():
    df.at[idx, "amount"] = row["amount"] * 1.1

# Good (fast) df["amount"] = df["amount"] * 1.1 ``` - Use comprehensions for simple transformations: They’re 2-10x faster than loops.

Readability

  • Limit nested if statements: Use early returns or helper functions.
    ```python # Bad (nested) if condition1:
    if condition2:
    do_something()

# Good (flat) if not condition1:
return if not condition2:
return do_something() `` - Name variables clearly:is_fraud>flag,cleaned_data>df2`.

Error Handling

  • Log before raising exceptions:
    python try:
    df = pd.read_csv("data.csv") except FileNotFoundError as e:
    print(f"ERROR: File not found. Details: {e}")
    raise
  • Use try-except for data validation:
    python try:
    df["amount"] = df["amount"].astype(float) except ValueError:
    print("ERROR: 'amount' column contains non-numeric values.")

Testing

  • Test edge cases: Empty DataFrames, NaN values, mixed data types.
  • Use assert for sanity checks:
    python assert len(df) > 0, "DataFrame is empty!" assert df["amount"].dtype == float, "'amount' column is not numeric!"


5. ⚠️ Common Mistakes & Traps

Mistake Symptom Fix/Prevention
Modifying a list while iterating RuntimeError: list changed size during iteration Iterate over a copy (for item in list.copy():).
Infinite while loop Script hangs forever. Add a safety counter (max_iterations = 1000).
Using == for NaN if df["col"].isna() == True: fails. Use pd.isna() or df["col"].isna().
Nested loops on DataFrames Script runs for hours. Use merge() or join() instead.
Ignoring else in loops else block runs even if loop breaks. Remember: else runs only if the loop completes normally.


6. ? Exam/Certification Focus


Question Patterns

  1. Comprehension vs. Loop:
  2. "Which is faster: a list comprehension or a for loop?"
    Answer: Comprehension (Python optimizes it).

  3. if-elif-else Order:

  4. "What’s the output of this code?"
    python
    x = 10
    if x > 5:
    print("A")
    elif x > 8:
    print("B")
    else:
    print("C")

    Answer: A (only the first True condition runs).

  5. break vs. continue:

  6. "What does this loop print?"
    python
    for i in range(5):
    if i == 2:
    continue
    if i == 4:
    break
    print(i)

    Answer: 0, 1, 3 (continue skips 2, break exits at 4).

  7. try-except Scope:

  8. "Which exception does this catch?"
    python
    try:
    x = 1 / 0
    except ZeroDivisionError:
    print("Error!")

    Answer: Only ZeroDivisionError (not TypeError or ValueError).

Key Traps

  • else in loops: Runs only if the loop completes without a break.
  • is vs. ==: is checks identity (memory address), == checks equality.
  • Mutable default args: Never use def foo(x=[]):—it retains state between calls.


7. ? Hands-On Challenge

Task: Write a function that takes a list of numbers and returns a new list with: - Even numbers doubled.
- Odd numbers replaced with "ODD".
- Negative numbers skipped.

Example Input: [1, 2, -3, 4, 5] Expected Output: ["ODD", 4, 8, "ODD"]

Solution

def transform_numbers(numbers):
return [
num * 2 if num % 2 == 0 else "ODD"
for num in numbers
if num >= 0
]

Why it works:
- Comprehension filters (if num >= 0) and transforms (num * 2 or "ODD") in one line.
- Ternary operator (x if condition else y) handles the even/odd logic.


8. ? Rapid-Reference Crib Sheet

Concept Syntax Example Notes
if-elif-else if x > 0: ... elif x < 0: ... else: ... if age >= 18: print("Adult") Order matters!
for loop for item in sequence: ... for row in df.iterrows(): ... Avoid on large DataFrames.
while loop while condition: ... while len(df) > 0: ... Add a safety counter!
List comprehension [x for x in sequence if condition] [x*2 for x in nums if x > 0] Faster than loops.
Dict comprehension {k: v for k, v in dict.items()} {k: v*2 for k, v in d.items()} Use for transformations.
break if x > 10: break for i in range(100): if i > 50: break Exits the loop.
continue if x < 0: continue for num in nums: if num < 0: continue Skips to next iteration.
try-except try: ... except Error: ... try: x = 1/0 except ZeroDivisionError: ... Log errors!
enumerate() for idx, val in enumerate(seq): ... for i, row in enumerate(df): ... Tracks index.
zip() for a, b in zip(seq1, seq2): ... for x, y in zip(df1["a"], df2["b"]): ... Parallel iteration.
⚠️ else in loops for x in seq: ... else: ... for x in nums: if x > 10: break else: print("Done") Runs if no break.


9. ? Where to Go Next

  1. Python Official Docs – Control Flow (Start here for fundamentals.)
  2. Real Python – Comprehensions (Deep dive into list/dict/set comprehensions.)
  3. Pandas User Guide – Iteration (When to use iterrows() vs. vectorization.)
  4. Python for Data Analysis (O’Reilly) (Chapter 3 covers control flow in data science.)


ADVERTISEMENT