Booleans & Truthiness

Published by Brayan K

Truthiness is Python's rule that every value is treated as either "truthy" or "falsy" in a boolean context, so any object — not just True and False — can control an if or while.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A condition asks a question about a value

A value can be used in a condition without already being a Boolean. The bool() function lets you inspect the truth value that Python uses. For common built-in values, zero and empty containers are false; a nonzero number or a nonempty container is true. The sign of a number does not matter: negative numbers are not the same thing as false.

samples = [
    ("zero", 0),
    ("negative", -2),
    ("missing", None),
    ("empty text", ""),
    ("empty list", []),
    ("one zero", [0]),
    ("empty range", range(0)),
]
for label, value in samples:
    print(label, bool(value))

# ✅ Expected output:
# zero False
# negative True
# missing False
# empty text False
# empty list False
# one zero True
# empty range False

The indentation and branch structure of an if statement belong to Control Flow: Making Decisions in Python. This lesson is about the value that statement tests, and the mistakes caused by treating “false” as a synonym for “missing”.

False values come in several types

False and None are false in a condition. So are numeric zeroes, including floating-point and complex zero, and empty built-in sequences and collections. An empty dictionary is written as braces; an empty set needs set(), because braces already mean a dictionary.

from decimal import Decimal
from fractions import Fraction

groups = [
    ("constants", [False, None]),
    ("numeric zeroes", [0, 0.0, -0.0, 0j, Decimal("0"), Fraction(0, 1)]),
    ("empty sequences", ["", b"", bytearray(), [], (), range(0)]),
    ("empty collections", [{}, set(), frozenset()]),
]
for label, values in groups:
    print(label, [bool(value) for value in values])
print("nonempty:", bool({"enabled": False}), bool(b"0"))

# ✅ Expected output:
# constants [False, False]
# numeric zeroes [False, False, False, False, False, False]
# empty sequences [False, False, False, False, False, False]
# empty collections [False, False, False]
# nonempty: True True

The last line tests the containers, not their contents: one dictionary entry and one byte are enough. These values share a false truth value, but they are not interchangeable data. An empty dictionary can still hold entries later; None cannot. Use the category your input contract calls for.

Nonempty text does not parse itself

The characters inside a string do not become Python values just because the string looks like a number or a Boolean. A form field or configuration file can contain the text "false", but bool() only sees that the text is nonempty. A space is also a character. Normalise text and compare the actual words when a field has a defined vocabulary.

print(bool("False"), bool("0"), bool(" "))
setting = " false "
normalised = setting.strip().lower()
enabled = normalised == "true"
print(normalised)
print(enabled)
print(bool(" ".strip()))

# ✅ Expected output:
# True True True
# false
# False
# False

The enabled comparison recognises only the word true. If your input contract allows only true and false, reject other words as invalid rather than silently treating a misspelling as a real choice. A truth test checks emptiness; it does not validate a username, email address or setting.

Inspect the container, or inspect its contents

A list containing a false value is still a nonempty list. bool(results) asks whether the list contains any items. any(results) asks whether at least one item is truthy. all(results) asks whether every item is truthy. These are three different questions, and confusing them can make a failed set of checks look successful.

results = [False, False]
print(bool(results))
print(any(results))
print(all(results))

results = [True, False]
print(any(results), all(results))
print(any([]), all([]))

# ✅ Expected output:
# True
# False
# False
# True False
# False True

For an empty iterable, any() finds no true item and all() finds no false item. If an empty submission must fail, first require a nonempty collection as well as passing items. These functions test truth values, not a rule you have left unstated: a negative mark is nonzero, so it passes a plain all(scores).

scores = [-3, 5]
print(all(scores))
positive = [score > 0 for score in scores]
print(positive)
print(all(positive))
checks = []
print(bool(checks) and all(checks))

# ✅ Expected output:
# True
# [False, True]
# False
# False

The expression inside the list comprehension converts each score into a Boolean result before all() tests it. List, Dict & Set Comprehensions explains how that transformation is built.

A fallback can erase a legitimate zero

The operators and and or can return an operand instead of a Boolean; Operators and Expressions in Python owns their evaluation rules. When using them to choose a fallback, decide which values your application is allowed to discard.

quantity = 0
print(quantity or 1)
if quantity is None:
    quantity = 1
print(quantity)

title = ""
print(title or "Untitled")

# ✅ Expected output:
# 1
# 0
# Untitled

Replacing an empty title may be the intended rule. Replacing a quantity of zero may accidentally create an order the person did not request. Use an explicit absence check when zero, False or empty text are valid data. The meaning of that absence marker is developed in None & NoneType.

None & NoneType distinguishes an absent value from a present value that happens to be false.

Put the safe check before the operation

Short-circuiting can protect an operation only when the guard comes first. Comparing a missing reading with a number is already an error; putting an absence check afterwards cannot undo it.

reading = None
print(reading > 0 and reading is not None)

# ✅ Expected error:
# TypeError: '>' not supported between instances of 'NoneType' and 'int'

Check for the absence marker on the left. When it is absent, and stops without attempting the comparison. This tests positive readings; it deliberately rejects a real reading of zero because zero is not positive.

for reading in [None, 0, 4]:
    is_positive = reading is not None and reading > 0
    print(reading, is_positive)

# ✅ Expected output:
# None False
# 0 False
# 4 True

A custom object can define its own truth behaviour, and a truth test can raise an exception. Do not assume every object outside the built-in examples is true; Magic Methods & the Python Data Model explains the __bool__ and __len__ protocols.

Check a row of supplied names

Treat text made entirely of spaces as missing. Fill the blanks to turn each cleaned name into a Boolean, then report whether any name was supplied and whether all names were supplied. This checks presence only; it does not decide whether a name is valid.

names = ["Ada", "   ", "Lin"]
supplied = [bool(___) for name in names]
print(supplied)
print(any(supplied))
print(___ and all(supplied))

# 👉 replace ___ with name.strip()
# 👉 replace ___ with bool(supplied)

# ✅ Expected output:
# [True, False, True]
# True
# False

Decide whether a review can be submitted

A review is ready only when it contains at least one check and every check passed. Write the readiness calculation for an empty list, a list containing two true values, and a list containing one true and one false value. Print the result for each list. Do not use the length of the list as a substitute for inspecting its contents.

reviews = [[], [True, True], [True, False]]
for checks in reviews:
    ready = bool(checks) and all(checks)
    print(ready)

# ✅ Expected output:
# False
# True
# False

Practice quiz

What does this program print? print(bool("False"))

  • False
  • True
  • None
  • A ValueError

Answer: True. The string contains characters; bool does not parse its spelling.

What does this program print? print(bool([0]))

  • False
  • 0
  • None
  • True

Answer: True. The outer list contains one item.

What does this program print? print(any([]), all([]))

  • False True
  • False False
  • True True
  • True False

Answer: False True. There is no true item for any and no false item to disprove all.

What does this program print? print(0 or 7)

  • 0
  • True
  • 7
  • False

Answer: 7. The zero is falsy, so or returns its right operand.

What does this program print? print(all([-1, 2]))

  • False
  • True
  • -1
  • A TypeError

Answer: True. Both numbers are nonzero; all does not mean all-positive.

What does this program print? print(bool(" "), bool(" ".strip()))

  • False False
  • True True
  • False True
  • True False

Answer: True False. A space is nonempty text; stripping it leaves an empty string.

What does this program print? print(False and (1 / 0))

  • False
  • True
  • 0
  • A ZeroDivisionError

Answer: False. and stops at the false left operand.

What does this program print? print(bool(0j), bool(()), bool({}), bool({"ok": False}))

  • False False False False
  • True False False True
  • False False False True
  • False True True True

Answer: False False False True. Complex zero and empty containers are false; the dictionary with one entry is nonempty even though its value is False.

Continue this course

Related lessons