elseAdvanced Examples

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

else in all three contexts

Comprehensive use of else with if, loops, and try.

python
# All three uses of else
def find_and_process(data, target):
    # try/else: handle import errors
    try:
        from math import sqrt
    except ImportError:
        print("No math module")
    else:
        print(f"sqrt available: {sqrt(16)}")

    # for/else: search pattern
    for i, val in enumerate(data):
        if val == target:
            print(f"Found {target} at index {i}")
            break
    else:
        print(f"{target} not in data")

    # if/else: process result
    if target in data:
        idx = data.index(target)
        if idx % 2 == 0:
            print("Found at even index")
        else:
            print("Found at odd index")
    else:
        print("Cannot process: not found")

find_and_process([10, 20, 30, 40], 30)
print()
find_and_process([10, 20, 30, 40], 99)

Python uses 'else' in three contexts: if/else (condition), for-else/while-else (no break), and try/else (no exception). Each serves a different purpose.

Want to try these examples interactively?

Open Advanced Playground