Decisions as values

Lesson 2 of 20 · Functional Python: values, behavior, and choices

An expression is evaluated to produce a value. An assignment or return is a statement that can contain an expression. A call such as len(text) is an expression; it may also have effects, depending on the function.

def label(count: int) -> str:
    return "no readings" if count == 0 else "readings available"

print(label(0))
print(label(4))
no readings
readings available

In a if condition else b, Python evaluates the condition first, then only the chosen expression. Here count == 0 selects the first string for zero and the second otherwise. For several complicated cases, an if statement can be easier to read.

Returning and displaying are different: print displays output and returns None; a function with no explicit return also returns None. An expression can call print or modify data, so expression syntax alone does not guarantee a lack of effects.

Chapter index