Python Master Course V2 — 008. Boolean Values, Comparisons & Logical Thinking
Module 01 · Python foundations · Lesson 008 / 200
Boolean Values, Comparisons & Logical Thinking
Level: Beginner → Professional Foundations | Study: 70–100 minutes plus practice | Prerequisites: Lessons 001–007 (variables, numbers, strings)
Core idea: Real software constantly asks questions: Is this input valid? Is the user eligible? Is a payment due? Should a process continue? In Python, those questions become Boolean expressions and decision rules.
In this lesson · 22 sections + self-check
- 🎬 Lesson 008 Video Classroom
- 🎯 Learning Objectives
- 1. The Boolean Data Type: Two Possible Values
- 2. The Six Core Comparison Operators
- 3. Compare Strings Carefully
- 4. Equality (==) Is Not Identity (is)
- 5. Truthiness: How Python Interprets Values in Conditions
- 6. Logical and, or, and not
- 7. A Subtlety Professionals Must Know: and and or Return Operands
- 8. Short-Circuit Evaluation: Safer and Faster Decisions
- 9. Precedence and Parentheses
- 10. Chained Comparisons and Range Checks
- 11. Numeric Accuracy in Conditions
- 12. Conditions Drive if / elif / else
- 13. Practical Real-World Application: Access Eligibility
- 14. Guided Mini-Project: Robust Event Eligibility Checker
- 15. Common Mistakes and Debugging Clinic
- 16. Professional Design and Best Practices
- 17. Guided Practice Lab
- 18. Independent Exercises and Advanced Challenge
- 19. Knowledge Check (Try Before Revealing the Answers)
- 20. Lesson Summary and Next Steps
- Interactive self-check
🎬 Lesson 008 Video Classroom
Video title: Boolean Logic & Comparisons in Python — Lesson 008
Video status: Not yet uploaded. The reserved area will accept an embedded lesson video or an accessible external video URL when available.
Suggested video chapters: 00:00 Why logic matters · 07:00 True/False · 15:00 Comparisons · 28:00 Truthiness · 40:00 and/or/not · 54:00 Short-circuiting · 66:00 Decision project.
Video URL: To be added by course administrator; no placeholder link points to a nonexistent video.
🎯 Learning Objectives
After completing the lesson, you will be able to distinguish the two Boolean values from text representing them, apply all six core comparison operators, explain object identity versus equality, reason about truthy and falsy values, combine conditions with and, or and not, predict operator precedence and short-circuit evaluation, guard unsafe operations, and design and test a small real-world eligibility checker.
Prerequisite Self-Check
Confirm you can assign a value (age = 18), print an expression (print(age >= 18)), recognize a string ("18") and an integer (18), and run a .py file. If any item feels unfamiliar, revisit Lessons 005–007 first.
1. The Boolean Data Type: Two Possible Values
A Boolean expresses a binary logical result: True or False, with initial capital letters. The Python type is bool. Comparisons and many built-in predicates produce Boolean results.
is_active = True
has_expired = False
print(is_active, type(is_active))
print(has_expired, type(has_expired))Output: True <class 'bool'> and False <class 'bool'> on separate lines. Python keywords are case-sensitive: true is not the Boolean literal.
Professional distinction: True is not the same object or type as "True". One is a Boolean, the other is a string containing four letters.
print(True == "True") # False
print(type("False")) # <class 'str'>
print(bool("False")) # True: nonempty string!Do not use bool(user_text) to parse yes/no text. A string containing the word “False” is still nonempty and therefore truthy.
2. The Six Core Comparison Operators
Comparisons answer whether two values satisfy a relation. For numbers and supported comparable data, use == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal) and <= (less than or equal). Do not confuse == with assignment =.
a = 12
b = 20
print(a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= 12) # True
print(b <= 20) # TrueExample: Age Eligibility
age = 21
minimum_age = 18
eligible = age >= minimum_age
print("Eligible:", eligible) # Eligible: TrueNotice how naming the result eligible makes code more communicative than printing an unexplained comparison.
3. Compare Strings Carefully
String equality compares contents exactly; by default, capitalization and whitespace matter. Ordering strings compares Unicode code points lexicographically, not natural-language meaning. Normalize deliberate user-facing identifiers before comparing, and recognize that Unicode normalization is a separate concern for complex multilingual inputs.
entered = " PYTHON "
expected = "python"
print(entered == expected) # False
print(entered.strip().casefold() == expected) # TrueCase folding is useful for many informal text comparisons. It is not a universal security-grade identifier normalization strategy; authentication and identity systems require explicit design.
print("apple" == "Apple") # False
print("banana" > "apple") # True
print("10" < "2") # True: text comparison, not numericRule: If you intend to compare quantities supplied as text, validate them and convert them to numbers before comparison.
4. Equality (==) Is Not Identity (is)
Equality asks whether values compare equal. Identity asks whether references point to the same object. Two separate lists can be equal yet not identical. Do not use is to compare numbers, strings or arbitrary values; interpreter interning can make accidental tests appear to work.
first = [1, 2, 3]
second = [1, 2, 3]
alias = first
print(first == second) # True
print(first is second) # False
print(first is alias) # TrueUse is None and is not None when checking the unique None sentinel:
discount_code = None
if discount_code is None:
print("No discount code supplied")Unlike if not discount_code, the identity test distinguishes missing data from empty text and other falsy values.
5. Truthiness: How Python Interprets Values in Conditions
Python lets many objects participate in Boolean contexts. Common falsy values include False, None, numeric zero (0, 0.0), and empty collections or text ("", [], {}, set()). Most other ordinary values are truthy.
values = [False, None, 0, 0.0, "", [], {}, "0", [0], -5]
for value in values:
print(repr(value), "→", bool(value))Expected: the first seven values are False; "0", [0] and -5 are True. The contents of a nonempty container do not make the container falsy.
When Truthiness Is Appropriate
items = ["Python", "SQL"]
if items:
print("Cart has items")
display_name = ""
if not display_name:
print("Please enter a display name")Prefer explicit validation when 0, an empty collection, and missing data carry different meanings.
6. Logical and, or, and not
Use and when every condition must hold, or when at least one condition must hold, and not when you want the logical opposite.
age = 23
has_id = True
has_invitation = False
print(age >= 18 and has_id) # True
print(has_id or has_invitation) # True
print(not has_invitation) # TrueCompact Truth Table
| A | B | A and B | A or B |
|---|---|---|---|
| False | False | False | False |
| False | True | False | True |
| True | False | False | True |
| True | True | True | True |
not True yields False and not False yields True.
Example: Access Rule
is_staff = True
account_enabled = True
has_training = False
may_enter = account_enabled and (is_staff or has_training)
print(may_enter) # TrueThe parentheses make the intended policy clear to the next developer reviewing it.
7. A Subtlety Professionals Must Know: and and or Return Operands
In Python, these operators do not always return a Boolean. and returns the first falsy operand or the last operand. or returns the first truthy operand or the last operand. This behavior enables default values but can introduce surprising type errors.
print("" or "Guest") # Guest
print(0 or 100) # 100
print("ready" and 42) # 42
print([] and "continue") # []Pitfall: count = supplied_count or 10 incorrectly replaces an intentional 0 with 10. Where only absence should trigger a default, write:
supplied_count = 0
count = 10 if supplied_count is None else supplied_count
print(count) # 0If a function’s contract requires a Boolean result, make that contract explicit with comparisons or bool(...) when appropriate.
8. Short-Circuit Evaluation: Safer and Faster Decisions
Python evaluates A and B from left to right. If A is falsy, Python need not evaluate B. With A or B, a truthy A means B is skipped. This can prevent exceptions and avoid unnecessary work.
denominator = 0
safe_to_divide = denominator != 0 and (100 / denominator) > 5
print(safe_to_divide) # False; no ZeroDivisionErrorBetter in production: name guard conditions clearly rather than burying side effects inside Boolean expressions.
def is_long_name(value):
print("Checking length...")
return len(value) > 8
name = ""
result = bool(name) and is_long_name(name)
print(result) # False; helper never calledAvoid writing functions whose essential side effects depend on whether another condition short-circuits.
9. Precedence and Parentheses
Among the logical operators covered here, not binds more tightly than and, and and binds more tightly than or. Comparisons such as >= are evaluated before these logical combinations. Use parentheses in policy code even when you know precedence.
a = True
b = False
c = False
print(a or b and c) # True: a or (b and c)
print((a or b) and c) # False
print(not a or b) # False: (not a) or bOperator precedence is not a substitute for clarity. If a rule spans more than two conditions, identify and name intermediate predicates.
10. Chained Comparisons and Range Checks
Python supports natural mathematical range syntax. Unlike writing two separate checks, chained comparisons evaluate the middle expression only once.
score = 87
print(0 <= score <= 100) # True
print(18 <= 20 < 65) # True
print(1 < 2 < 3) # TrueDo not confuse chained comparisons with value membership or equality-to-either-choice:
choice = "yes"
print(choice in {"yes", "y"}) # True
# Incorrect approach: choice == ("yes" or "y")
# ("yes" or "y") evaluates to "yes", not a two-item comparison.Use in with a set, tuple or list when testing membership against several allowed values.
11. Numeric Accuracy in Conditions
Binary floating-point values are approximations, so equality may not behave as expected after arithmetic. Use math.isclose for numerical tolerance-based comparisons; use Decimal for monetary calculations where decimal rounding rules matter.
import math
print(0.1 + 0.2 == 0.3) # False in usual Python float arithmetic
print(math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)) # Truefrom decimal import Decimal
subtotal = Decimal("0.10") + Decimal("0.20")
print(subtotal == Decimal("0.30")) # TrueAdvanced caution: NaN is unordered and does not compare equal to itself. This matters in scientific and data work.
import math
value = float("nan")
print(value == value) # False
print(math.isnan(value)) # True12. Conditions Drive if / elif / else
Boolean expressions power control flow. Python uses indentation to define the body of each branch. A readable decision tree should consider the most restrictive invalid states before success cases.
score = 76
if not 0 <= score <= 100:
print("Invalid score")
elif score >= 90:
print("Excellent")
elif score >= 60:
print("Passed")
else:
print("Needs improvement")Output: Passed. Only the first matching branch executes. The leading validation protects the later grading rules from impossible inputs.
13. Practical Real-World Application: Access Eligibility
Consider an event system: the event must be open, the participant must be an adult, their account must be active, and they must have either a paid ticket or an approved invitation. Translate requirements from plain language into named predicates.
event_open = True
age = 20
account_active = True
ticket_paid = False
has_invitation = True
adult = age >= 18
has_entry_right = ticket_paid or has_invitation
eligible = event_open and adult and account_active and has_entry_right
print("Entry permitted:", eligible) # Entry permitted: TrueBecause the rules are named, it is easier to explain a denied result and to write focused tests. For a real production system, client-side or tutorial-level checks must not replace authoritative server-side authorization.
14. Guided Mini-Project: Robust Event Eligibility Checker
Project brief: Implement reusable functions that parse user answers and evaluate eligibility. Reject malformed input rather than quietly accepting ambiguous responses. Keep parsing and decision logic separate so each piece can be tested independently.
Step A — Parse Explicit Yes/No Answers
def parse_yes_no(text: str) -> bool:
normalized = text.strip().casefold()
if normalized in {"yes", "y"}:
return True
if normalized in {"no", "n"}:
return False
raise ValueError("Enter yes/y or no/n.")
assert parse_yes_no(" YES ") is True
assert parse_yes_no("n") is FalseWhy? Using bool("no") would return True. Validating a known vocabulary avoids that bug.
Step B — Write One Pure Decision Function
def may_attend(
age: int,
event_open: bool,
account_active: bool,
paid: bool,
invited: bool,
) -> bool:
if age < 0:
raise ValueError("Age cannot be negative.")
is_adult = age >= 18
has_permission = paid or invited
return event_open and is_adult and account_active and has_permissionThe function is deterministic and returns a Boolean, so it is easy to test without a database or a user interface.
Step C — Integrate Inputs and Error Handling
def main() -> None:
try:
age = int(input("Age: ").strip())
paid = parse_yes_no(input("Paid ticket? yes/no: "))
invited = parse_yes_no(input("Approved invitation? yes/no: "))
result = may_attend(
age=age,
event_open=True,
account_active=True,
paid=paid,
invited=invited,
)
except ValueError as error:
print("Input error:", error)
else:
print("Eligible for entry:", result)
if __name__ == "__main__":
main()How to run: save the code from Steps A, B and C into one file named eligibility_checker.py, then run python eligibility_checker.py (or your environment’s equivalent command). All function definitions must be present in the same file or imported before main() executes.
Step D — Verify the Core Rules
assert may_attend(21, True, True, True, False) is True
assert may_attend(21, True, True, False, True) is True
assert may_attend(17, True, True, True, True) is False
assert may_attend(21, False, True, True, True) is False
assert may_attend(21, True, False, True, True) is False
assert may_attend(21, True, True, False, False) is False
print("All core tests passed.")Professional extension: Return a structured decision result containing a Boolean and an explicit denial reason. This makes reports and audit trails easier to understand, but avoid exposing sensitive authorization details to untrusted users.
15. Common Mistakes and Debugging Clinic
Mistake 1: Confusing = and ==
age = 18 # Assign a value.
print(age == 18) # Compare values: True.if age = 18: is a syntax error. Use == for equality in a condition.
Mistake 2: Incorrect Boolean Capitalization
Write True and False, not true, FALSE or quoted versions.
Mistake 3: Misreading a Nonempty String
answer = "False"
print(bool(answer)) # True
print(answer.casefold() == "true") # FalseMistake 4: Unintended Use of is
Use x == y for value equality. Use x is None for the sentinel and identity tests only when identity is the actual requirement.
Mistake 5: Writing x == 10 or 20
x = 7
print(x == 10 or 20) # 20; truthy, not a correct test
print(x == 10 or x == 20) # False
print(x in (10, 20)) # FalseMistake 6: Missing Parentheses
For multi-condition rules, group logic explicitly and write one assertion per expected behavior.
Debugging Workflow
- Reproduce the input that caused the wrong result.
- Print types as well as values:
print(repr(value), type(value)). - Break compound conditions into named intermediate predicates.
- Test true, false and boundary cases independently.
- Use a small assertion or debugger to narrow down which predicate was wrong.
- Fix the underlying validation rule rather than adding a special-case print statement.
16. Professional Design and Best Practices
- Choose intention-revealing names:
has_access,is_valid,can_submit. - Prefer direct Boolean variables:
if enabled:overif enabled == True:. - Use
is Nonewhen missing data and falsy values must be distinguished. - Use explicit parentheses for compound authorization or payment rules.
- Avoid mixing input collection, validation and business rules in one giant conditional.
- Convert raw inputs to validated types before making important decisions.
- Keep decision functions pure where possible and test both branches and edge cases.
- For monetary values, use
Decimalwhen decimal financial accuracy is required. - Do not rely on this beginner example for production authentication or sensitive access control without trusted identity, server-side checks and security review.
17. Guided Practice Lab
Lab 1 — Shipping policy: A package ships only when payment is complete and stock is available. Create two Boolean variables and one combined condition; test all four input combinations.
Hint: shipping policy
Both conditions must hold. Enumerate False/False, False/True, True/False and True/True.
Worked answer: shipping policy
for paid, in_stock in [(False, False), (False, True), (True, False), (True, True)]:
may_ship = paid and in_stock
print(paid, in_stock, may_ship)Expected output:
False False False
False True False
True False False
True True TrueOnly the final combination satisfies both requirements. Using or would wrongly permit an unpaid order or unavailable stock.
Lab 2 — Grade boundaries: Write a predicate for scores from 0 to 100 inclusive and test -1, 0, 100 and 101.
Hint: grade boundaries
Use one chained comparison with inclusive endpoints.
Worked answer: grade boundaries
for score in [-1, 0, 100, 101]:
valid = 0 <= score <= 100
print(score, valid)Expected output:
-1 False
0 True
100 True
101 FalseThe endpoint values are valid; values immediately outside the range are rejected. This checks validity rather than whether a learner passed.
Lab 3 — Optional profile text: Treat None as “not provided” and "" as “provided but empty.” Demonstrate why is None is useful.
Hint: optional profile text
Check identity with None before comparing with the empty string.
Worked answer: optional profile text
for profile in [None, "", "Sam"]:
if profile is None:
status = "not provided"
elif profile == "":
status = "provided but empty"
else:
status = "provided text"
print(repr(profile), status)Expected output:
None not provided
'' provided but empty
'Sam' provided textnot profile would combine the first two cases. An explicit absence check preserves the distinction required by the policy.
Lab 4 — Short-circuit guard: Accept a list and check its first value only when the list is nonempty:
numbers = []
first_is_positive = bool(numbers) and numbers[0] > 0
print(first_is_positive) # FalseHint: short-circuit guard
Check that the list has an element before reading index zero.
Worked answer: short-circuit guard
for numbers in [[], [0], [3]]:
first_is_positive = bool(numbers) and numbers[0] > 0
print(numbers, first_is_positive)Expected output:
[] False
[0] False
[3] TrueFor the empty list the right operand is skipped, so no IndexError occurs. The Boolean conversion also makes the result consistently True or False.
Lab 5 — Prediction: Before running the code, predict the exact value and type of "" or 0 or "Ready" and [1] and 0. Then check with repr() and type().
Hint: operand values and types
or stops at the first truthy operand; and stops at the first falsey operand.
Worked answer: operand values and types
for value in ["" or 0 or "Ready", [1] and 0]:
print(repr(value), type(value).__name__)Expected output:
'Ready' str
0 intThe first expression reaches the nonempty string; the second reaches the integer zero after a truthy list. These operators return operand values, so neither result is automatically Boolean.
18. Independent Exercises and Advanced Challenge
- Create a login eligibility predicate requiring an active account and verified email.
- Write a condition that permits a discount when the user is a member or the order total is at least 1,000.
- Use a chained comparison to test whether a temperature is between 18 and 28 inclusive.
- Fix
if user_choice == "yes" or "y":and explain the original error. - Compare two independently created lists using
==andis. - Demonstrate that
"0"and0have different truthiness. - Write a two-step fallback that preserves a deliberately supplied zero.
- Extend the mini-project with a configurable minimum age and a maximum capacity check.
Challenge Project — Rule-Based Order Approval
Design approve_order(total, stock, paid, priority, account_active). A basic order is approvable when its total is positive, stock is at least one, payment is complete and the account is active. Priority alone must never bypass a missing payment. Make the policy explicit, return a Boolean, provide at least eight assertions including invalid and boundary values, and write one paragraph explaining the security implications of using untrusted flags. Stretch: use Decimal for total and refuse inconsistent data types.
19. Knowledge Check (Try Before Revealing the Answers)
- What Python type contains
TrueandFalse? - What does
bool("False")return, and why? - What is the difference between
==andis? - What does
not (True and False)evaluate to? - Does
"Guest" or "Member"return a Boolean? - Why does
0.1 + 0.2 == 0.3usually returnFalse? - What is short-circuit evaluation?
- Which comparison is best for checking a missing
Nonevalue? - Which condition is safer:
age >= 18 and has_idor two unrelatedifblocks that independently grant entry? - How would you validate the literal yes/no input string
"no"?
View Answer Key
bool.True, because the string is nonempty.- Value equality versus object identity.
True.- No; it returns the string
"Guest". - Binary floating-point representation introduces approximation; consider
math.isclose. - Skipping later operand evaluation once the result is already determined.
value is None.- The single combined
andrule, because both conditions must hold. - Normalize and match against an explicit approved vocabulary such as
{"yes", "y"}and{"no", "n"}.
20. Lesson Summary and Next Steps
You now know how Python represents truth, compares values, evaluates compound conditions, decides whether containers are truthy, short-circuits logical operations, distinguishes equality from identity, and converts real requirements into testable decision functions. These concepts underpin validation, workflows, web requests, APIs, automation, analytics and eventually AI application logic.
Mastery checkpoint: Without consulting this page, write and test a Boolean function with at least four conditions and explain why each condition is necessary. If you can predict the output and types of the and/or examples, you are ready to move on.
Apply what you learned
Interactive self-check
Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.
This is a practice quiz. Results are saved on this browser when storage is available.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.