Conditional Expressions That Choose a Value

A conditional expression chooses one value for use inside a larger expression or as the result of a function.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Choose one displayed quantity
  2. Check the result type
  3. Read both possible types at the call site
  4. Keep calculation and presentation at separate boundaries

Choose one displayed quantity

Given a known number of seats, show the number when it is available and "unknown" when the count is None. In Python a conditional expression evaluates its condition and only the selected branch. This follows the same general decision behavior as if and else statements.

Check the result type

If another routine multiplies the result by a price, mixing a string placeholder and an integer is error-prone. Keep the optional integer until the boundary that formats a label. Parsing and formatting gives that display step a precise role.[1][2]

Read both possible types at the call site

Suppose a display wants the label "overdue" when a supplied deadline precedes today and "upcoming" otherwise. A conditional expression can choose one of the two strings at the point of display. Python evaluates its condition and the chosen branch. If one alternative produces a number and the other produces text, a later caller needs a contract accepting both types or a common representation. See values and supported operations.

Keep calculation and presentation at separate boundaries

A count may be unavailable. A display routine can choose a number's formatted spelling or the word unknown after it receives that optional count. The earlier function can still expose a numeric value or absence, which lets another consumer add valid counts without first parsing a display label. Parsing and formatting separates these tasks.

Test with a positive count, zero, and absence. A generic truth test would choose the absence form for zero. When a conditional expression starts hiding important effects or domain rules, an ordinary branch and an intermediate result can make the reasoning easier to follow. Verify that only the intended side runs under the language's evaluation model.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩