Boolean Operators in Python

Boolean operators allow your Python programs to make decisions by combining or inverting truth values. In this chapter, you’ll learn about comparison operators that produce Booleans, logical operators that combine them, how Python evaluates and short-circuits expressions, and finish with a mini-project that puts it all together.


What Are Boolean Values and Expressions?

A Boolean is one of two values: True or False. Any expression that evaluates to one of these is called a Boolean expression. Common sources of Boolean expressions include:

  • Comparisons: Checking if two values relate (e.g., x > y).
  • Membership tests: Verifying presence (e.g., 'a' in "cat").
  • Function returns: Many functions return True or False (e.g., isinstance(obj, list)).
print(10 > 5)        # True
print("py" in "python")  # True
print(isinstance(5, str)) # False

Comparison Operators

Comparison operators compare two values and yield a Boolean:

OperatorMeaningExampleResult
==Equal5 == 5True
!=Not equal5 != 3True
>Greater than7 > 10False
<Less than3 < 4True
>=Greater than or equal5 >= 5True
<=Less than or equal2 <= 1False
a, b = 8, 3
print(a > b)   # True
print(a == b)  # False

Use these to drive if statements, filters, and loops.


Logical Operators: and, or, not

Logical operators combine or invert Boolean expressions:

  • and returns True if both operands are True.
  • or returns True if at least one operand is True.
  • not inverts a Boolean: True → False, False → True.

Truth Tables

A       B       A and B    A or B     not A
True    True    True       True       False
True    False   False      True       False
False   True    False      True       True
False   False   False      False      True
x, y = True, False
print(x and y)  # False
print(x or y)   # True
print(not x)    # False

Short-Circuit Evaluation

Python’s and and or use short-circuit logic:

  • With and, if the first operand is False, the second is not evaluated.
  • With or, if the first operand is True, the second is not evaluated.
def expensive_check():
    print("Checking…")
    return True

# Second call skipped because first is False
if False and expensive_check():
    pass

# Second call skipped because first is True
if True or expensive_check():
    pass

Short-circuiting can prevent unnecessary computation or even errors (e.g., checking for None before accessing attributes).


Truthiness and Falsiness

Beyond Booleans, many Python objects have an implicit truth value:

  • Falsy: 0, 0.0, "", [], {}, set(), None
  • Truthy: Nearly everything else (nonzero numbers, nonempty containers)
if []:
    print("Won’t print")
if "hello":
    print("This prints because the string is nonempty")

Use this feature to write concise checks (e.g., if items: instead of if len(items) > 0:).


Operator Precedence and Grouping

Python evaluates Boolean expressions in this order:

  1. not
  2. and
  3. or

Use parentheses to make complex conditions clear:

# Without parentheses: a or b and c  → a or (b and c)
result = a or b and c

# Explicit grouping:
result = (a or b) and c

Mini Project: User Access Validator

Create a function that determines if a user can perform an action based on multiple Boolean flags:

from typing import NamedTuple

class User(NamedTuple):
    is_active: bool
    is_admin: bool
    has_profile: bool

def can_post(user: User) -> bool:
    """
    User can post only if they are active,
    and either an admin or have completed their profile.
    """
    return user.is_active and (user.is_admin or user.has_profile)

# Examples
users = [
    User(True, False, False),
    User(True, False, True),
    User(True, True, False),
    User(False, True, True)
]

for u in users:
    print(u, "→ can post?", can_post(u))

What This Teaches:

  • Combining flags with and/or.
  • Using parentheses for grouping.
  • Returning Boolean results directly.

Conclusion

Boolean operators are the backbone of conditional logic in Python. By mastering:

  • Comparison operators to generate Boolean values
  • Logical operators (and, or, not) to combine them
  • Short-circuit behavior and truthiness rules
  • Precedence and grouping for clarity

you’ll write code that makes smart, precise decisions. Practice by crafting functions that validate user input, filter data, or enforce business rules—all powered by Boolean logic.


Discover more from Affordable Tutor

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top