Python - Booleans

Overview

Estimated time: 15–20 minutes

Learn truthiness, boolean operators, and common patterns in conditions.

Learning Objectives

  • Use True and False; understand truthy and falsy values.
  • Apply and, or, and not correctly with short-circuiting.
  • Prefer explicit comparisons for clarity (e.g., if x is None).

Prerequisites

Truthiness

# Falsy: 0, 0.0, '', [], {}, set(), None, False
# Truthy: most other values

items = []
if not items:
    print("No items")

Boolean operators

x, y = 0, 5
print(x and y)  # 0 (returns first falsy)
print(x or y)   # 5 (returns first truthy)
print(not x)    # True

Common Pitfalls

  • Expecting and/or to return booleans; they return operands.
  • Using == None instead of is None.

Checks for Understanding

  1. What does [] or 'fallback' evaluate to?
  2. How do you test for None?
Show answers
  1. 'fallback'
  2. if x is None:

Exercises

  1. Use short-circuiting to pick the first non-empty string from three variables.
  2. Write a predicate that returns True for non-empty sequences.