# Control Flow & Loops

> Explain Python's control flow mechanisms including loops, conditionals, and the match statement.

Canonical: https://www.internhack.in/learn/interview/python-interview/python-control-flow
Last updated: 2026-11-28

Difficulty: Beginner

## Question

Explain Python's control flow mechanisms including loops, conditionals, and the match statement.

## Answer

Python's control flow includes:

- if/elif/else: Conditional branching with truthiness checks
- for loops: Iterate over any iterable (list, range, dict, string, file)
- while loops: Loop while condition is true
- break/continue/pass: Loop control
- for/while...else: The else clause runs if the loop completes WITHOUT a break
- match/case (Python 3.10+): Structural pattern matching

Python has no switch statement (before 3.10), no do-while, and no traditional C-style for loop. Ternary: x = a if condition else b.

## Code examples

### Loop Patterns and else Clause

```
# for...else: else runs if no break
def find_prime_factor(n):
    for i in range(2, n):
        if n % i == 0:
            print(f"Smallest factor of {n}: {i}")
            break
    else:
        # Only runs if loop completed without break
        print(f"{n} is prime!")

find_prime_factor(17)  # 17 is prime!
find_prime_factor(15)  # Smallest factor of 15: 3

# enumerate for index + value
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

# zip for parallel iteration
names = ['Alice', 'Bob']
scores = [95, 87]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
```

The for...else pattern is unique to Python. The else block runs only if the loop exits normally (no break). enumerate() and zip() are essential Pythonic patterns.

### Ternary and Walrus Operator

```
# Ternary expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # 'adult'

# Chained comparisons
x = 5
print(1 < x < 10)    # True (equivalent to 1 < x and x < 10)
print(1 < x > 3)     # True

# Walrus operator := (Python 3.8+)
# Assigns and returns value in one expression
import re
text = "Hello World 42"
if (match := re.search(r'\d+', text)):
    print(f"Found number: {match.group()}")  # 'Found number: 42'

# Walrus in while loop
while (line := input("Enter (q to quit): ")) != 'q':
    print(f"You said: {line}")

# Walrus in list comprehension
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = [y for x in nums if (y := x  2) > 20]
print(results)  # [25, 36, 49, 64, 81, 100]
```

The walrus operator (:=) assigns a value inside an expression, reducing repetition. Chained comparisons are more readable than using 'and'.

### match/case (Python 3.10+)

```
# Structural pattern matching
def handle_command(command):
    match command.split():
        case ["quit"]:
            return "Goodbye!"
        case ["hello", name]:
            return f"Hello, {name}!"
        case ["add", *numbers]:
            return sum(int(n) for n in numbers)
        case _:
            return "Unknown command"

print(handle_command("quit"))         # 'Goodbye!'
print(handle_command("hello Alice"))  # 'Hello, Alice!'
print(handle_command("add 1 2 3"))   # 6

# Pattern matching with guards
def classify(value):
    match value:
        case int(n) if n > 0:
            return "positive int"
        case int(n) if n < 0:
            return "negative int"
        case 0:
            return "zero"
        case str(s) if len(s) > 0:
            return "non-empty string"
        case _:
            return "other"
```

match/case goes beyond simple value matching - it can destructure sequences, match types, capture variables, and use guard conditions.

## Key points

- Python uses indentation (not braces) for blocks - convention is 4 spaces
- pass is a no-op placeholder for empty blocks: if True: pass
- match/case is NOT the same as switch/case - it does structural pattern matching

## Common follow-up questions

- What is the difference between match/case and if/elif chains?
- How does the walrus operator help avoid repeated computations?
- What are the performance implications of different loop patterns?

## Interview tips

- Know enumerate() and zip() - using range(len()) is considered un-Pythonic
- The for...else pattern is a great way to show Python depth
- Mention the walrus operator for Python 3.8+ code

## Concepts covered

if/elif/else, for loops, while loops, break/continue, else clause on loops, match/case

Previous: [Dictionaries & Operations](https://www.internhack.in/learn/interview/python-interview/python-dictionaries) · Next: [Functions & Arguments](https://www.internhack.in/learn/interview/python-interview/python-functions) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [\*args & kwargs](https://www.internhack.in/learn/interview/python-interview/python-args-kwargs)
- [List Comprehensions](https://www.internhack.in/learn/interview/python-interview/python-list-comprehensions)
- [Lambda, Map, Filter, Reduce](https://www.internhack.in/learn/interview/python-interview/python-lambda-map-filter)
- [OOP: Classes & Objects](https://www.internhack.in/learn/interview/python-interview/python-oop)
- [Inheritance & MRO](https://www.internhack.in/learn/interview/python-interview/python-inheritance-mro)
- [Magic/Dunder Methods](https://www.internhack.in/learn/interview/python-interview/python-dunder-methods)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
