elseIntermediate Examples

Catch-all branch when preceding if/elif conditions are all false

else with for and while loops

Loop else runs when the loop completes without break.

python
# for/else: check if a number is prime
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False  # could use break + else here too
    return True

# Using for/else pattern
for n in [17, 18, 19, 20]:
    for i in range(2, n):
        if n % i == 0:
            print(f"{n} = {i} x {n//i}")
            break
    else:
        print(f"{n} is prime")
Expected Output
17 is prime
18 = 2 x 9
19 is prime
20 = 2 x 4

Loop else is unusual: it runs when the loop finishes normally (without break). Think of it as 'nobreak' — it runs if break was never hit.

else with try/except

Running code only when no exception occurred.

python
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print(f"Cannot divide {a} by zero")
    else:
        print(f"{a} / {b} = {result}")
    finally:
        print("---")

safe_divide(10, 3)
safe_divide(10, 0)
Expected Output
10 / 3 = 3.3333333333333335
---
Cannot divide 10 by zero
---

try/else runs only when no exception was raised. Put code here that should only run on success, keeping the try block minimal.

Want to try these examples interactively?

Open Intermediate Playground