Conditionals & Loops
Control flow is what separates scripted data processing from static formulas. These patterns appear in every data pipeline, ETL script, and analysis function.
How do you write an if-elif-else statement in Python?
score = 75
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(grade) # "B"In Pandas, this logic is done with np.where() for two conditions or np.select() for multiple. But knowing the plain Python form is the foundation interviewers expect.
What is the difference between for and while loops?
# for — iterates over a sequence
for i in range(5):
print(i) # 0 1 2 3 4
# while — runs until condition is False
n = 0
while n < 5:
print(n)
n += 1Use for when you know the number of iterations. Use while for retry logic or reading streaming data until a condition is met. Forgetting to increment in while loops causes infinite loops.
How do you use enumerate() and zip() in loops?
# enumerate — get index + value
cols = ["name", "age", "city"]
for i, col in enumerate(cols):
print(i, col) # 0 name, 1 age, 2 city
# zip — loop over two lists together
keys = ["a", "b", "c"]
vals = [1, 2, 3]
for k, v in zip(keys, vals):
print(k, v)enumerate() replaces the pattern for i in range(len(lst)): — cleaner and Pythonic. zip() is used to pair column names with values, or two DataFrames row by row.
What are break, continue, and pass?
# break — exit the loop entirely
for i in range(10):
if i == 5:
break # stops at 5
# continue — skip to next iteration
for i in range(5):
if i == 2:
continue # skips 2
print(i) # 0 1 3 4
# pass — do nothing (placeholder)
if True:
pass # no error, loop/block continuesbreak is used to stop searching once you find what you need. continue skips bad rows in a loop. pass is a placeholder when building stub functions or empty branches.
How do you write a one-line conditional (ternary operator)?
x = 10
result = "positive" if x > 0 else "non-positive"
print(result) # "positive"
# In list comprehension:
flags = ["high" if v > 100 else "low" for v in [50, 150, 80, 200]]The ternary form is used heavily in list comprehensions and Pandas .apply() lambdas. It is cleaner than a full if-else for simple single-value decisions.
EVIKA ACADEMY · PYTHON FOR DATA ANALYTICS
Want to master Python with live practice?
Join our Python for Data Analysis course — live classes in Noida and online across India.
Book Free Demo Class →