Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 10

Booleans, Comparisons and Logical Operators

Build and combine true-or-false expressions that programs can use to make reliable decisions.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026

Lesson 10: Booleans, Comparisons and Logical Operators

1. Introduction to Boolean Logic in Programming

In computer science and digital circuit design, decision-making relies entirely on binary logic—a system where statements evaluate to one of two fundamental values: True (1) or False (0). Named after mathematician George Boole, Boolean algebra forms the backbone of software control flow.

In Python, Boolean values are represented using the built-in bool data type. Whether you are validating a user login password, checking account balance sufficiency before a banking withdrawal, or determining if a game character has run out of health points, Python evaluates conditions using Boolean expressions, comparison operators, and logical logic gates.


2. Deep Dive: The `bool` Data Type in Python

1. Literal Values and Case Sensitivity

Python provides two fundamental Boolean literals: True and False. Python is strictly case-sensitive—writing true, TRUE, false, or FALSE in lowercase or uppercase will cause Python to raise a NameError, treating them as undefined variable names.

Python Internal Architecture: In Python, bool is an explicit subclass of int. Internally, True inherits directly from integer 1 and False inherits from integer 0.
BOOL_SUBCLASS_DEMO.PY
# Demonstrating that bool is a subclass of int
is_python_fun = True
has_errors = False

print("Value:", is_python_fun, "| Type:", type(is_python_fun))
print("Is bool a subclass of int?", issubclass(bool, int))

# Arithmetic operations on Booleans (True = 1, False = 0)
print("True + True =", True + True)
print("True * 50 =", True * 50)
print("False - True =", False - True)
OUTPUT
Value: True | Type: 
Is bool a subclass of int? True
True + True = 2
True * 50 = 50
False - True = -1

3. Truth Value Testing: Truthy and Falsy Objects

Python allows any built-in object to be tested for a Boolean truth value. When an object is evaluated inside a conditional statement or explicitly passed to the bool() constructor function, Python maps that object to either True (termed Truthy) or False (termed Falsy).

1. Exhaustive List of Falsy Objects in Python

Every object in Python is Truthy EXCEPT the following explicit built-in Falsy objects:

  • Built-in Constants: None and False.
  • Numeric Zeros: Integer 0, floating-point 0.0, complex zero 0j, Decimal(0), and Fraction(0, 1).
  • Empty Sequences and Collections: Empty string "", empty list [], empty tuple (), empty dictionary {}, empty set set(), and empty range range(0).
Crucial Nuance: Non-empty containers containing Falsy elements evaluate to True! For instance, a list containing zero [0] or a string containing whitespace " " are non-empty objects, so bool([0]) and bool(" ") both evaluate to True.
TRUTHY_FALSY_CHECK.PY
# Testing Falsy objects
print("bool(0)        ->", bool(0))
print("bool(0.0)      ->", bool(0.0))
print("bool('')       ->", bool(""))
print("bool([])       ->", bool([]))
print("bool(None)     ->", bool(None))

print("--- Testing Truthy edge cases ---")
# Whitespace string is NOT empty!
print("bool(' ')      ->", bool(" "))
# List containing zero is NOT empty!
print("bool([0])      ->", bool([0]))
OUTPUT
bool(0)        -> False
bool(0.0)      -> False
bool('')       -> False
bool([])       -> False
bool(None)     -> False
--- Testing Truthy edge cases ---
bool(' ')      -> True
bool([0])      -> True

4. Comparison (Relational) Operators

Comparison operators compare the values of two operands and evaluate to a Boolean result (True or False).

  • ==
  • Equal To
  • Operands hold equivalent values
  • 10 == 10.0
  • True
  • !=
  • Not Equal To
  • Operands hold different values
  • "python" != "Java"
  • True
  • >
  • Greater Than
  • Left operand is strictly greater than right
  • 15 > 25
  • False
  • <
  • Less Than
  • Left operand is strictly smaller than right
  • 5.5 < 8.2
  • True
  • >=
  • Greater Than or Equal To
  • Left operand is greater or equal to right
  • 10 >= 10
  • True
  • <=
  • Less Than or Equal To
  • Left operand is smaller or equal to right
  • 7 <= 3
  • False
  • Operator Formal Name Mathematical Condition Tested Example Code Evaluated Result

    Chained Comparison Operators (Pythonic Feature)

    In C++ or Java, checking if a value lies within an interval requires combining expressions using logical AND: (x >= 10 && x <= 20). Python natively supports chained comparisons, allowing developers to write clean mathematical expressions like 10 <= x <= 20.

    CHAINED_COMPARISONS.PY
    score = 85
    
    # Chained Comparison Syntax
    is_grade_a = 80 <= score <= 90
    print("Is Score within Grade A range (80-90)?", is_grade_a)
    
    # Multi-variable chained comparisons
    a, b, c = 5, 10, 15
    print("Is a < b < c ?", a < b < c)
    print("Is a < b > c ?", a < b > c)
    OUTPUT
    Is Score within Grade A range (80-90)? True
    Is a < b < c ? True
    Is a < b > c ? False

    5. Logical Operators (`and`, `or`, `not`)

    Logical operators allow combining multiple Boolean conditions to build complex execution logic.

    1. Truth Tables for Logical Operators

  • True
  • True
  • True
  • True
  • False
  • True
  • False
  • False
  • True
  • False
  • False
  • True
  • False
  • True
  • True
  • False
  • False
  • False
  • False
  • True
  • Operand A Operand B A `and` B A `or` B `not` A

    6. Deep Dive: Short-Circuit Evaluation in Python

    Python's logical operators and and or utilize an optimization technique called Short-Circuit Evaluation. Instead of always returning a strict Boolean True or False, they evaluate from left to right and return the **actual operand object** that stopped evaluation!

    How Short-Circuit Evaluation Works:

    • `X and Y` Rules: Evaluates X first. If X is Falsy, Python immediately returns X without evaluating Y (because the overall result is guaranteed to be Falsy). If X is Truthy, Python evaluates and returns Y.
    • `X or Y` Rules: Evaluates X first. If X is Truthy, Python immediately returns X without evaluating Y (because the overall result is guaranteed to be Truthy). If X is Falsy, Python evaluates and returns Y.
    Guarding Against Errors: Short-circuiting allows developers to write defensive code safeguards. For example, in if count != 0 and total / count > 5:, if count is 0, the left side evaluates to False and Python stops immediately, preventing a fatal ZeroDivisionError on the right side!
    SHORT_CIRCUIT_DEMO.PY
    # Short-Circuiting with 'or' (Returning default fallback values)
    user_provided_name = ""
    default_name = "Guest User"
    
    # Returns user_provided_name if Truthy, otherwise falls back to default_name
    display_name = user_provided_name or default_name
    print("Display Name:", display_name)
    
    # Short-Circuiting guarding against ZeroDivisionError
    items_count = 0
    total_sum = 100
    
    # Division is never executed because items_count != 0 evaluates to False!
    safe_check = items_count != 0 and (total_sum / items_count) > 10
    print("Safe Division Check Result:", safe_check)
    OUTPUT
    Display Name: Guest User
    Safe Division Check Result: False

    7. Identity Operators (`is` vs `is not`) vs Value Equality (`==` vs `!=`)

    Beginning Python developers often confuse value equality (==) with object identity (is).

    • Value Equality (`==`): Compares whether the **contents and values** of two objects are equivalent.
    • Object Identity (`is`): Compares whether two variables point to the **exact same memory address ID** in heap memory (equivalent to id(a) == id(b)).
    IDENTITY_VS_EQUALITY.PY
    # Creating two distinct list objects containing identical elements
    list1 = [1, 2, 3]
    list2 = [1, 2, 3]
    
    print("list1 == list2 :", list1 == list2) # True (Same content value)
    print("list1 is list2 :", list1 is list2) # False (Different memory objects!)
    
    print("Memory ID List 1:", id(list1))
    print("Memory ID List 2:", id(list2))
    
    # Alias referencing the exact same object
    list3 = list1
    print("list1 is list3 :", list1 is list3) # True (Same memory object!)
    OUTPUT
    list1 == list2 : True
    list1 is list2 : False
    Memory ID List 1: 140239482910224
    Memory ID List 2: 140239482911856
    list1 is list3 : True
    PEP 8 Guideline for `None`: Always use identity operators is or is not when testing for None (e.g., if var is None:), rather than == None.

    8. Membership Operators (`in` and `not in`)

    Membership operators test whether a specified element or substring exists inside a sequence or collection (such as strings, lists, tuples, sets, or dictionaries).

    MEMBERSHIP_DEMO.PY
    allowed_roles = ["admin", "editor", "moderator"]
    current_user_role = "editor"
    
    print("Is Editor allowed?", current_user_role in allowed_roles)
    print("Is Guest allowed?", "guest" in allowed_roles)
    
    # Membership testing in strings
    sentence = "Python Programming Mastery"
    print("'Python' in sentence?", "Python" in sentence)
    print("'java' not in sentence?", "java" not in sentence)
    OUTPUT
    Is Editor allowed? True
    Is Guest allowed? False
    'Python' in sentence? True
    'java' not in sentence? True

    9. Operator Precedence Hierarchy

    When an expression mixes comparison, identity, membership, and logical operators, Python follows strict operator precedence order:

    1. Arithmetic Operators (**, *, /, //, %, +, -)
    2. Comparison & Relational Operators (==, !=, >, <, >=, <=)
    3. Identity & Membership Operators (is, is not, in, not in)
    4. Logical not
    5. Logical and
    6. Logical or

    10. Frequently Asked Interview Questions with Answers

    Q1: Why does `bool` inherit from `int` in Python?
    Answer: Historically in early Python versions, dedicated Boolean types did not exist; integers 1 and 0 represented truth values. When bool was introduced in PEP 285, it was implemented as a subclass of int to maintain complete backward compatibility. Consequently, True == 1 and False == 0 evaluate to True.
    Q2: What is Short-Circuit Evaluation, and what does `[] or "Default"` evaluate to?
    Answer: Short-circuit evaluation means Python's logical operators and/or evaluate expressions from left to right and stop as soon as the outcome is finalized, returning the actual operand object. For [] or "Default", since [] is Falsy, the or operator evaluates and returns the second operand: "Default".
    Q3: What is the difference between `x == y` and `x is y`?
    Answer: x == y checks **value equality** (whether the contents of objects $x$ and $y$ are equivalent). x is y checks **object identity** (whether variables $x$ and $y$ point to the exact same memory address ID in heap memory).
    Q4: Why is `bool([0])` True while `bool([])` is False?
    Answer: Python evaluates container objects based on whether they are empty or non-empty. An empty list [] contains zero elements and is Falsy. A list containing zero [0] is a non-empty container holding one element, making it Truthy.
    Q5: Why should you use `is None` instead of `== None` in Python?
    Answer: None is a unique singleton object in Python memory. Using is None compares memory identity directly, which is faster and safer than == None (which can be overridden or spoofed if custom classes overload the __eq__() magic method).

    11. Homework & Practical Assignment

    Task 1: Truthiness Audit Matrix

    Evaluate the Truthiness (True or False) for each expression without running the code first:

    1. bool("False")
    2. bool(0.0000001)
    3. bool(None or [])
    4. 10 and "Python"
    5. "" or 50

    Task 2: User Access Validator Script

    Create a script named access_validator.py inside your lesson_10 folder:

    • Prompt for user age (integer) and account status (string: "active" or "suspended").
    • Check if age is greater or equal to 18 AND account status is "active" using logical and.
    • Print access grant decision using Boolean expressions.

    Task 3: Safe Division Guard Exercise

    Write a script named safe_divider.py that accepts two numbers, uses short-circuiting logical and to guard against division by zero, and prints the result without throwing a ZeroDivisionError.


    12. File & Workspace Directory Structure

    Standard Course Workspace Layout:

    Ensure all exercise files are stored inside their corresponding lesson directories:

    python_mastery_course/
    │
    ├── lesson_01/
    ├── lesson_02/
    ├── lesson_03/
    ├── lesson_04/
    ├── lesson_05/
    ├── lesson_06/
    ├── lesson_07/
    ├── lesson_08/
    ├── lesson_09/
    │
    └── lesson_10/
        ├── bool_subclass_demo.py
        ├── truthy_falsy_check.py
        ├── chained_comparisons.py
        ├── short_circuit_demo.py
        ├── identity_vs_equality.py
        ├── membership_demo.py
        ├── access_validator.py
        └── safe_divider.py
            

    13. What We Will Learn Next

    Next Up: Lesson 11 — Decision Making with if, elif and else

    Now that you master Boolean conditions, logical truthiness, and comparison operators, we will learn how to branch program execution dynamically.

    In the next lesson, we will cover:

    • The if statement execution block and indentation control flow.
    • Multi-branch conditional decision trees using elif and fallback else blocks.
    • Nested conditional statements and avoiding deeply nested code code-smells.
    • The Conditional Ternary Operator (x if condition else y) for single-line inline assignments.
    • Pattern Matching with match-case statements (Python 3.10+ modern syntax).

    📝 Live Lesson Practice

    HTML/CSS JavaScript Python C++ C PHP
    ⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
    💻 Code Editor (Monaco VS Code Engine)
    👀 Live Preview
    Address Contact

    +91 7877547686

    E-mail

    onlinecbtportal@gmail.com

    Helpline Number

    +91 7877547686


    Click To Download
    Get it on Google Play

    ऐप डाउनलोड करने
    के लिए Google Play पर
    उपलब्ध है

    WhatsApp Chat