Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Conditional control flow

An if statement tests its conditions in order and executes the first truthy branch.

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

Syntax

if condition:
    first()
elif alternative:
    second()
else:
    fallback()

An if statement tests its conditions in order and executes the first truthy branch.

An optional else handles the case in which no test succeeds. Empty collections and zero are false. An object can define __bool__, or fall back to __len__.

The empty-list branch returns before items[0] is read. The three classifications are empty, negative and other.

events=[]
def check(n):
    events.append(n)
    return n
if check(0): raise AssertionError
elif check(1): pass
elif check(2): raise AssertionError
assert events==[0,1]
class Switch:
    def __bool__(self): return False
assert not Switch() and not [] and bool([0])

Examples

def classify(items):
    if not items:
        return "empty"
    elif items[0] < 0:
        return "negative"
    else:
        return "other"

print([classify(v) for v in ([], [-2], [0])])

Result

['empty', 'negative', 'other']

The empty-list branch returns before items[0] is read. The three classifications are empty, negative and other.

Sources