By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
(if-elif-else, for/while loops, comprehensions)
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).
customer_id
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).
if
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").
if-elif-else
NaN
None
for
df.apply()
numpy
while
True
max_iterations = 1000
break
continue
try-except
KeyError
ValueError
enumerate()
zip()
df1['id']
df2['name']
Task: You’re given a CSV of e-commerce transactions with missing values, duplicates, and outliers. Clean it using control flow.
pandas
pip install pandas numpy
transactions.csv
order_id
amount
category
import pandas as pd df = pd.read_csv("transactions.csv") print(f"Original shape: {df.shape}")
# 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"])
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.")
# 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.")
# Standardize category names (e.g., "groceries" -> "Groceries") df["category"] = [cat.strip().title() for cat in df["category"]]
df.to_csv("transactions_cleaned.csv", index=False) print("Cleaned data saved to 'transactions_cleaned.csv'.")
Original shape: (10000, 4) Flagged 42 outliers for review.Removed 123 duplicates.Cleaned data saved to 'transactions_cleaned.csv'.
# Good (fast) df["amount"] = df["amount"] * 1.1 ``` - Use comprehensions for simple transformations: They’re 2-10x faster than loops.
# Good (flat) if not condition1: return if not condition2: return do_something() `` - Name variables clearly:is_fraud>flag,cleaned_data>df2`.
`` - Name variables clearly:
>
,
python try: df = pd.read_csv("data.csv") except FileNotFoundError as e: print(f"ERROR: File not found. Details: {e}") raise
python try: df["amount"] = df["amount"].astype(float) except ValueError: print("ERROR: 'amount' column contains non-numeric values.")
assert
python assert len(df) > 0, "DataFrame is empty!" assert df["amount"].dtype == float, "'amount' column is not numeric!"
RuntimeError: list changed size during iteration
for item in list.copy():
==
if df["col"].isna() == True:
pd.isna()
df["col"].isna()
merge()
join()
else
"Which is faster: a list comprehension or a for loop?" Answer: Comprehension (Python optimizes it).
if-elif-else Order:
"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).
python x = 10 if x > 5: print("A") elif x > 8: print("B") else: print("C")
A
break vs. continue:
"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).
python for i in range(5): if i == 2: continue if i == 4: break print(i)
0, 1, 3
2
4
try-except Scope:
python try: x = 1 / 0 except ZeroDivisionError: print("Error!")
ZeroDivisionError
TypeError
is
def foo(x=[]):
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.
"ODD"
Example Input: [1, 2, -3, 4, 5] Expected Output: ["ODD", 4, 8, "ODD"]
[1, 2, -3, 4, 5]
["ODD", 4, 8, "ODD"]
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.
if num >= 0
num * 2
x if condition else y
if x > 0: ... elif x < 0: ... else: ...
if age >= 18: print("Adult")
for item in sequence: ...
for row in df.iterrows(): ...
while condition: ...
while len(df) > 0: ...
[x for x in sequence if condition]
[x*2 for x in nums if x > 0]
{k: v for k, v in dict.items()}
{k: v*2 for k, v in d.items()}
if x > 10: break
for i in range(100): if i > 50: break
if x < 0: continue
for num in nums: if num < 0: continue
try: ... except Error: ...
try: x = 1/0 except ZeroDivisionError: ...
for idx, val in enumerate(seq): ...
for i, row in enumerate(df): ...
for a, b in zip(seq1, seq2): ...
for x, y in zip(df1["a"], df2["b"]): ...
for x in seq: ... else: ...
for x in nums: if x > 10: break else: print("Done")
iterrows()
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.