liveBook · Manning

Boolean

As explained in The Quick Python Book, Fourth Edition

A boolean value is a truth-valued value that is either true or false.

A Python boolean is either `True` or `False`. Boolean values drive conditional tests in `if` statements and loops, but a condition need not be a boolean object: most Python objects can be tested directly. section 8.11 section 8.11.1

In a conditional test, these values count as false:

  • `False`, `None`, and numeric zero, including `0.0` and `0+0j`. section 3.4.1 section 8.11.1
  • Empty strings and containers: `""`, `[]`, `{}`, and `set()`. Nonempty strings and containers count as true. section 8.11.1
  • Nonzero numbers count as true. Some objects, such as file and code objects, lack a sensible empty-or-zero interpretation and are best avoided as conditions. section 8.11.1

Comparisons such as `==` and `!=` produce boolean results. Use `in` or `not in` for membership, and `is` or `is not` to test whether references identify the same object. Combine tests with `and`, `or`, and `not`; use parentheses when a complex expression’s grouping might be unclear. section 8.11.2

A range test

`if 0 < x and x < 10:` can be written `if 0 < x < 10:`. Also, `x = False; not x` evaluates to `True`, while `True * 2` evaluates to `2`: booleans behave like `1` and `0` in arithmetic. section 8.11.2 section 3.2.1

[2] and [3, 4]
 
[3, 4]             #1
 
[] and 5
 
[]                 #2
 
[2] or [3, 4]
 
[2]                #2
 
[] or 5
 
5                  #1
#1 The second element must be evaluated.
#2 Only the first element needs to be evaluated.

The outputs show a subtle distinction: `and` and `or` return an operand, not necessarily `True` or `False`. Evaluation stops once an operand determines the result. section 8.11.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains truth rules and operators through small examples, including operand-returning short-circuit behavior; defers detailed precedence rules to Python documentation.
Examples
Uses empty containers, a chained range test, boolean arithmetic, and list-valued `and` and `or` expressions.
What it assumes
Assumes familiarity with standard numeric operations; introduces Python-specific truth testing without requiring prior knowledge of every container type.
What you can do after
Evaluate/understand it by predicting conditional truth values and recognizing when `and` or `or` returns an operand.
How it connects
Connects booleans to control flow, comparisons, membership tests, object identity, and logical operators.

Also explained in

Compare how 11 books explain boolean →

Related concepts

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