elseExpert Examples

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

Else bytecode across contexts

How else compiles differently in each context.

python
import dis

def if_else():
    if True:
        return 1
    else:
        return 2

def for_else():
    for i in range(3):
        pass
    else:
        return "done"

def try_else():
    try:
        pass
    except:
        return "error"
    else:
        return "ok"

print("if/else:")
dis.dis(if_else)
print("\nfor/else:")
dis.dis(for_else)
print("\ntry/else:")
dis.dis(try_else)

if/else uses conditional jumps. for/else places the else block after FOR_ITER (break jumps past it). try/else places the else code after the except handler.

Want to try these examples interactively?

Open Expert Playground