2. Control Flow

Understand branching and looping patterns that make code clear and concise.

Question: How do you control loop execution?

Answer: Use break to exit a loop immediately, continue to skip to the next iteration, and pass as a placeholder that does nothing.

Explanation: Python loops also have an optional else block that executes only if the loop completes normally (i.e., it was not terminated by a break statement). This is useful for search loops.

for i in [1, 2, 3]:
    if i == 4:
        break
else:
    print("4 was not found.") # This will run

Question: What are enumerate and zip used for?

Answer: enumerate iterates over a sequence while providing both the index and the value. zip iterates over multiple sequences in parallel.

# enumerate example
for i, x in enumerate(['A', 'B', 'C']):
    print(i, x)  # Prints 0 A, 1 B, 2 C

# zip example
for num, letter in zip([1, 2], ["x", "y"]):
    print(num, letter) # Prints 1 x, 2 y

Question: What is the walrus operator := and when should you use it?

Answer: It assigns and returns a value in a single expression, useful to avoid repeating expensive calls or to shorten loops/conditions.

if (n := len(items)) > 0:
    print(f"We have {n} items")

while (line := f.readline().strip()):
    process(line)

Question: What is match/case (structural pattern matching)?

Answer: A concise way to branch on the structure and values of data (Python 3.10+), supporting literals, sequences, mappings, guards, and class patterns.

def http_status(status: int) -> str:
    match status:
        case 200 | 204:
            return "OK"
        case 400:
            return "Bad Request"
        case s if 500 <= s < 600:
            return "Server Error"
        case _:
            return "Unknown"

Question: How do you write a one-line conditional?

Answer: Use the conditional expression x if condition else y.

status = "adult" if age >= 18 else "minor"