Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword else

After if, else handles the path where no condition matched.

Version: Python 3.14; repository image, production runtime not attested

Syntax

if test:
    ...
else:
    ...

After if, else handles the path where no condition matched.

A loop else runs on normal exhaustion or a false while condition, including zero iterations, and is skipped by break. A try else runs when its try suite finishes without an exception or a return, break or continue transfer.

Exceptions raised in try-else bypass that try’s except handlers.

Examples

def locate(target, rows):
    for v in rows:
        if v == target:
            break
    else:
        return "absent"
    return "found"
def parse(s):
    try:
        n = int(s)
    except ValueError:
        return "invalid"
    else:
        return "zero" if n == 0 else "number"
print(locate(0, []), locate(0, [0]), parse("0"), parse("x"))

Result

absent found zero invalid

Exceptions raised in try-else bypass that try’s except handlers.

Sources