Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword if

Evaluate a condition using Python truth testing rather than comparison with True.

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

Syntax

if condition:
    ...
else:
    ...

Evaluate a condition using Python truth testing rather than comparison with True.

Objects may implement __bool__ or, when that is absent, __len__. Only the selected suite executes. Conditions linked with and or or may short-circuit without evaluating every operand.

A true __bool__ takes precedence even if __len__ returns zero.

Examples

class Stock:
    def __init__(self, units):
        self.units = units
    def __len__(self):
        return self.units
for item in (Stock(0), Stock(2)):
    if item:
        print("ready")
    else:
        print("empty")
class Priority(Stock):
    def __bool__(self):
        return True
if Priority(0):
    print("bool wins")

Result

empty
ready
bool wins

A true `__bool__` takes precedence even if `__len__` returns zero.

Sources