Thuta Learning
Python
BasicProgrammingBeginner

Python Booleans

PythonLesson 1120 min

What you'll walk away with

  • Write conditions using comparison operators that return True or False
  • Predict results of and, or and not, and control their order with parentheses
  • Recognise falsy values such as 0, "", [] and None and write checks like if items:
  • Spot and fix the always-True bug in role == "admin" or "editor"

Explain it simply

Explain it simply

A boolean is the answer to a yes-or-no question. There are only two values, True and False. In Python they start with a capital T and F and have no quotes; "True" in quotes is a string, not a boolean.

Programs use booleans every time they make a decision. Is the password right? Is there anything in the cart? Is this user an admin? Each answer is True or False, and an if statement uses that answer to choose which path to take.

Problem → Why → Solution

The problem: a viewer can see the Edit button

You want to show the Edit button only to admins and editors, so you write the condition below. Read aloud as English it sounds right: "if role is admin or editor". Yet the button appears even when role is "viewer"; in fact the condition is True for every role.

permissions.py
role = "viewer"

if role == "admin" or "editor":     # always True!
    print("Show Edit button")

# Python reads it as: (role == "admin") or ("editor")
#                     False             or  "editor"  -> "editor" (truthy)

Why is it always True?

or does not share the == between two values; it joins two separate expressions. The left side, role == "admin", is False, so Python evaluates the right side and gets the string "editor". Every non-empty string is truthy, so the if branch always runs. The correct versions are role == "admin" or role == "editor", or more simply role in ("admin", "editor").

Core concept: comparisons, logic and truthiness

Most boolean values come from comparisons. ==, !=, >, <, >= and <= compare the left and right sides and return True or False. Do not confuse = (assignment) with == (comparison). Python also lets you chain comparisons: 1 < x < 10 means the same as 1 < x and x < 10.

OperatorTrue whenExample
a and bboth sides are truthyTrue and False → False
a or bat least one side is truthyTrue or False → True
not aa is falsynot True → False

Every Python value has truthiness: put it in an if and it behaves like either True or False. The falsy values are a short list: False, None, 0, 0.0, the empty string "", the empty list [], the empty tuple (), the empty dict {} and the empty set. Everything else is truthy, so even " " (a single space) and [0] count as True. bool(value) shows that truthiness directly.

and and or short-circuit. If the left side of and is falsy, the right side is never evaluated and the left value is returned; the same happens with or when its left side is truthy. So and/or do not always return True or False; they return one of their operands, which is why nickname or "Guest" gives "Guest" when the nickname is empty. Precedence runs not first, then and, then or; add parentheses whenever a condition gets complicated.

One last detail: bool is a subclass of int. True equals 1 and False equals 0, so True + True is 2. That is why sum() can count how many times a condition was True.

Mental model: if asks about truthiness
  1. Comparisons produce True/False
  2. Every value is truthy or falsy
  3. and/or short-circuit left to right
  4. if tests the result's truthiness

if does not need the value True itself; any truthy value is enough, which is both useful and a source of bugs.

General pattern

python
is_ok = left == right            # comparison -> bool
in_range = low <= value < high   # chained comparison

both = condition_a and condition_b
either = condition_a or condition_b
opposite = not condition

if collection:                   # truthy when not empty
    ...
result = value or default        # first truthy operand

Comparisons produce booleans and and/or/not combine them. if collection: runs only when the collection is not empty, and value or default falls back to default when value is falsy.

Example: boolean values, comparisons, logic and truthiness

This example shows the type of True and False, then tries three comparisons and the three logical operators. The last part passes numbers, strings and lists to bool() to show that empty values are False. Before running it, cover the comments on the right and predict each line; the logical section is where most learners slip, because and needs both sides while or needs only one.

booleans.py
# ===== 1. Boolean Values =====
x = True
y = False

print(f"x = {x}, Type: {type(x)}")
print(f"y = {y}, Type: {type(y)}")

# ===== 2. Comparison Operations =====
print("\n===== Comparison =====")
print(f"10 > 5 = {10 > 5}")      # True
print(f"10 == 5 = {10 == 5}")    # False
print(f"10 < 5 = {10 < 5}")      # False

# ===== 3. Logical Operators =====
print("\n===== Logical Operators =====")
a = True
b = False

print(f"a and b = {a and b}")    # False
print(f"a or b = {a or b}")      # True
print(f"not a = {not a}")        # False

# ===== 4. Boolean Values of Objects =====
print("\n===== Boolean of Objects =====")
print(f"bool(0) = {bool(0)}")           # False
print(f"bool(1) = {bool(1)}")           # True
print(f"bool('') = {bool('')}")         # False
print(f"bool('Sai') = {bool('Sai')}")   # True
print(f"bool([]) = {bool([])}")         # False
print(f"bool([1,2,3]) = {bool([1,2,3])}")  # True

Code breakdown

  1. Line 5print(f"x = {x}, Type: {type(x)}")

    The type of True is <class 'bool'>. bool is a subclass of int, so True equals 1 and False equals 0.

  2. Line 11print(f"10 == 5 = {10 == 5}") # False

    == asks whether the values are equal; a single = assigns, so the two are never interchangeable.

  3. Lines 19-20print(f"a and b = {a and b}") # False

    a is True, so and has to check b and returns b, which is False. or, by contrast, stops as soon as it sees that a is True.

  4. Line 27print(f"bool('') = {bool('')}") # False

    The empty string is falsy and a string with characters, such as 'Sai', is truthy; the meaning of the text does not matter.

  5. Line 29print(f"bool([]) = {bool([])}") # False

    An empty list is False, so if cart: is enough to check whether the cart has items; len(cart) > 0 is unnecessary.

You should see
x = True, Type: <class 'bool'>
y = False, Type: <class 'bool'>

===== Comparison =====
10 > 5 = True
10 == 5 = False
10 < 5 = False

===== Logical Operators =====
a and b = False
a or b = True
not a = False

===== Boolean of Objects =====
bool(0) = False
bool(1) = True
bool('') = False
bool('Sai') = True
bool([]) = False
bool([1,2,3]) = True
How and short-circuits
  1. Evaluate the left operand
  2. If falsy, return it at once
  3. If truthy, evaluate the right side
  4. Return the right-hand value

Left is falsy

user and user.is_admin -> None (right side skipped)

Left is truthy

user and user.is_admin -> value of user.is_admin

any(), all() and counting booleans

To test a condition across many values, use two built-ins instead of a long chain of and/or. all(values) returns True only if every value is truthy, and any(values) returns True as soon as one is. Note that all([]) is True while any([]) is False: with nothing to check, nothing has failed. And because bool is an int, sum() counts how many values are True.

any_all.py
passed = [True, True, False, True]

print(all(passed))      # False: one test failed
print(any(passed))      # True: at least one passed
print(sum(passed))      # 3: True counts as 1
print(all([]), any([])) # True False

In real projects

Where this shows up in real projects

Every permission check is boolean logic: conditions like is_logged_in and (is_admin or is_owner) and not is_banned exist in every web app. Feature flags (ENABLE_NEW_CHECKOUT = True), form validation results (is_valid) and is_active database columns are booleans too. Starting boolean names with is_, has_ or can_ makes the code read like a sentence.

Short-circuiting is used daily as well. user and user.email never reads user.email when user is None, which prevents an AttributeError. Supplying defaults with name = form.get("name") or "Anonymous" is just as common. Where 0 is a legitimate value, such as a quantity or a discount, or would silently replace that 0 with the default, so test with is None instead. Test suites lean on booleans too: every assert statement simply checks that an expression is truthy.

Common mistakes

Common mistakes

1. Writing x == a or b

role == "admin" or "editor" always passes, because the string "editor" is truthy. Write role in ("admin", "editor"), which is shorter and much harder to get wrong.

2. Writing true or "True"

is_ready = true raises NameError: name 'true' is not defined (unlike JavaScript). Writing "True" in quotes creates a string, and the string "False" is truthy inside an if.

3. Writing if x == True:

if x == True: passes for x = 1 but not for "yes" or [1], which surprises people. For a boolean variable just write if is_ready:, and use if x is False: when you specifically need the False object.

4. Forgetting how tightly not binds

not a == b means not (a == b), not (not a) == b, because not runs after comparisons. Yet not a and b means (not a) and b. Rather than memorising these details, prefer the simpler a != b or add parentheses.

Best practices

Best practices

  • Name boolean variables like questions: is_active, has_items, can_edit.
  • Split a long condition into named variables for each part.
  • Test for None with is None, not == None.

Mini challenge

Mini challenge: an edit-permission check

Write a function that decides who may edit posts on a blog, plus one that returns "Guest" for an empty nickname.

  • can_edit(role, is_banned, is_owner): admins, editors or owners may edit, banned users never
  • Use and, or, not and parentheses in a single return statement
  • display_name(nickname) returns "Guest" even when the nickname is only spaces
  • Also print what the buggy 'viewer' == 'admin' or 'editor' evaluates to
can_edit.py
def can_edit(role: str, is_banned: bool, is_owner: bool) -> bool:
    # TODO: (admin or editor, or the owner) and not banned
    ...


def display_name(nickname: str) -> str:
    # TODO: strip the nickname and fall back to "Guest" with or
    ...


checks = [
    ("editor", False, False),
    ("viewer", False, True),
    ("admin", True, False),
    ("viewer", False, False),
]
# TODO: loop over checks and print each case with its can_edit result
# TODO: print display_name("  ") and display_name("Mya")
# TODO: print bool('viewer' == 'admin' or 'editor')

Expected: The program prints: editor, banned=False, owner=False -> True viewer, banned=False, owner=True -> True admin, banned=True, owner=False -> False viewer, banned=False, owner=False -> False display_name(' ') = Guest display_name('Mya') = Mya Buggy check gives: True

Show hint

role in ("admin", "editor") checks both roles at once. not binds tighter than and, but the or part needs parentheses; without them a banned admin could still edit. for role, banned, owner in checks: unpacks each tuple into three variables.

Show solution
can_edit.py
def can_edit(role: str, is_banned: bool, is_owner: bool) -> bool:
    """Admins and editors can edit, owners can edit their own post,
    and banned users can never edit."""
    return (role in ("admin", "editor") or is_owner) and not is_banned


def display_name(nickname: str) -> str:
    """Fall back to 'Guest' when the nickname is empty or only spaces."""
    return nickname.strip() or "Guest"


checks = [
    ("editor", False, False),
    ("viewer", False, True),
    ("admin", True, False),
    ("viewer", False, False),
]
for role, banned, owner in checks:
    print(f"{role}, banned={banned}, owner={owner} -> {can_edit(role, banned, owner)}")

print(f"display_name('  ') = {display_name('  ')}")
print(f"display_name('Mya') = {display_name('Mya')}")
print(f"Buggy check gives: {bool('viewer' == 'admin' or 'editor')}")

Quick quiz 1 / 3

What does print(0 or "zero", 5 and 7) output?

Quick quiz 2 / 3

Which of these values is truthy?

Quick quiz 3 / 3

With role = "guest", which condition evaluates as False?

What to remember

  • The two boolean values are True and False, and comparisons produce them.
  • and/or short-circuit and return one of their operands; precedence is not, and, or.
  • False, None, 0, 0.0 and empty collections are falsy; everything else is truthy.
  • Write x in (a, b), never x == a or b.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Booleans | Thuta Learning