Welcome to the first part of our exploration of Boolean values in Python! In this lecture, we'll cover the fundamental concepts of Boolean logic, which form the backbone of decision-making in programming.
Just as we make yes/no decisions in our daily lives, computers use Boolean values to determine which actions to take, which paths to follow, and how to process data. Understanding these concepts is crucial for writing effective Python code.
Booleans are one of Python's built-in data types that can have only two possible values: True or False. Named after mathematician George Boole, these values represent the concepts of truth and falsehood in programming logic.
In Python, Boolean values are written with capital first letters: True and False. This capitalization is important—using lowercase (true or false) will result in a NameError because Python is case-sensitive.
# Creating Boolean variables
is_sunny = True
is_raining = False
print(type(is_sunny)) # => <class 'bool'>
print(type(is_raining)) # => <class 'bool'>
# Comparing values produces Boolean results
print(10 > 5) # => True
print(10 < 5) # => False
Interestingly, in Python, bool is actually a subclass of int. This means True and False are special versions of the integers 1 and 0 respectively. This implementation detail allows for some interesting behavior:
# Booleans can be used in arithmetic
print(True + True) # => 2
print(True * 8) # => 8
print(False * 100) # => 0
# Converting between bool and int
print(int(True)) # => 1
print(int(False)) # => 0
print(bool(1)) # => True
print(bool(0)) # => False
This relationship between Booleans and integers is practical, but it's generally better to treat Booleans as logical values rather than numbers in your code for clarity.
Python provides three main Boolean operators for combining and manipulating Boolean values:
| Python Operator | JavaScript Equivalent | Description | Example |
|---|---|---|---|
and |
&& |
Logical AND: True if both operands are True | True and False → False |
or |
|| |
Logical OR: True if at least one operand is True | True or False → True |
not |
! |
Logical NOT: Inverts the truth value | not True → False |
The and operator requires both conditions to be True for the entire expression to be True:
# Logical AND truth table
print(True and True) # => True
print(True and False) # => False
print(False and True) # => False
print(False and False) # => False
# Real-world example
username = "admin"
password = "password123"
is_valid_login = (username == "admin") and (password == "password123")
print(is_valid_login) # => True
The or operator requires at least one condition to be True for the entire expression to be True:
# Logical OR truth table
print(True or True) # => True
print(True or False) # => True
print(False or True) # => True
print(False or False) # => False
# Real-world example
is_member = True
has_coupon = False
gets_discount = is_member or has_coupon
print(gets_discount) # => True
The not operator inverts a Boolean value, changing True to False and False to True:
# Logical NOT examples
print(not True) # => False
print(not False) # => True
# Real-world example
is_weekend = False
is_workday = not is_weekend
print(is_workday) # => True
# Combining operators
has_completed_tasks = True
is_deadline_passed = False
needs_attention = not has_completed_tasks or is_deadline_passed
print(needs_attention) # => False
Python uses short-circuit evaluation for Boolean operators. This means that in an expression like A and B, if A is False, Python doesn't evaluate B because the result will always be False. Similarly, in A or B, if A is True, it doesn't evaluate B because the result will always be True.
This behavior is not just an optimization; it's a feature you can use intentionally:
# Short-circuit evaluation with 'and'
x = 5
if x > 0 and 10/x > 1:
print("x is positive and 10/x is greater than 1")
# If x were 0, the second part (10/x) wouldn't be evaluated,
# avoiding a ZeroDivisionError
# Short-circuit evaluation with 'or'
def expensive_function():
print("Computing expensive result...")
return True
cached_result = False
result = cached_result or expensive_function()
print(result) # If cached_result is True, expensive_function() isn't called
In Python, every object has a truth value, meaning it can be evaluated as either True or False in a Boolean context (like an if statement). This feature is called "truth value testing."
Most objects in Python are considered True unless they meet specific criteria that make them False.
The following values are evaluated as False in a Boolean context:
False: The Boolean False valueNone: Python's null value0, 0.0, 0j: Zero in any numeric type"": Empty string[]: Empty list(): Empty tuple{}: Empty dictionaryset(): Empty set__bool__() to return False or __len__() to return 0
All values not listed above are considered True in a Boolean context, including:
__bool__() or __len__() methods# Testing various values in boolean context
def is_truthy(value):
if value:
return f"{value} is True"
else:
return f"{repr(value)} is False"
# Falsy values
print(is_truthy(False)) # => False is False
print(is_truthy(None)) # => None is False
print(is_truthy(0)) # => 0 is False
print(is_truthy("")) # => '' is False
print(is_truthy([])) # => [] is False
print(is_truthy({})) # => {} is False
# Truthy values
print(is_truthy(True)) # => True is True
print(is_truthy(42)) # => 42 is True
print(is_truthy(-1.5)) # => -1.5 is True
print(is_truthy("Hello")) # => Hello is True
print(is_truthy([1, 2, 3])) # => [1, 2, 3] is True
print(is_truthy({"a": 1})) # => {'a': 1} is True
This behavior allows for clean, readable code. For example, checking if a list is empty can be done with a simple if my_list: rather than if len(my_list) > 0:.
It's important to distinguish between Boolean operators (and, or, not) and comparison operators (==, !=, <, >, <=, >=):
# Comparison operators create Boolean expressions
x = 10
y = 5
print(x == y) # => False (x equals y?)
print(x != y) # => True (x not equal to y?)
print(x > y) # => True (x greater than y?)
print(x < y) # => False (x less than y?)
print(x >= y) # => True (x greater than or equal to y?)
print(x <= y) # => False (x less than or equal to y?)
# Combining comparison and Boolean operators
result = (x > 0) and (y > 0)
print(result) # => True
In this first part of our exploration of Boolean values in Python, we've covered:
True and Falseand, or, and notThese concepts form the foundation of logical operations in Python. In the next lecture, we'll explore practical applications of these concepts in real-world programming scenarios.
Next Steps: Continue to the exercises for this lecture to practice what you've learned, or proceed to the next lecture on Boolean Applications in Python.
© 2025 RMdelapaz All rights reserved.