liveBook · Manning

Boolean context

As explained in Python Workout, Second Edition

A Boolean context is a Python evaluation context in which an object's truth value determines control flow or a conditional result.

A Boolean context evaluates an object as true or false so Python can choose a control-flow path or conditional result. Empty sequences and empty strings evaluate as false; nonempty values evaluate as true. section 4.7 section 5.9

Use Boolean contexts to write direct guards instead of explicit length or equality checks:

  • Use `if not items` to detect that a variadic argument tuple is empty before indexing its first element. section 4.7
  • Use `if not city_name` to detect an empty input string and terminate or skip the current loop iteration. section 5.9
  • Prefer truth-value tests over checking sequence length or comparing directly with `()`. section 4.7

Guarding input and arguments

A function can begin with `if not items:` before reading `items[0]`; an input loop can use `if not city_name:` to reject an empty city name. section 4.7 section 5.9

How Python Workout, Second Edition covers it

How deep it goes
Explains empty tuples and strings through executable examples, without developing a broader theory of truth-value testing.
Examples
Demonstrates `if not items` for variadic arguments and `if not city_name` in a rainfall-entry loop.
What you can do after
Apply Python truth testing to write concise guards for empty collections and input strings.
How it connects
Connects truth values with sequences, strings, conditional statements, loops, tuples, and user input.

Also explained in

Compare how 2 books explain boolean context →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.