Booleans
Validate user passwords. Check if a file exists. Determine whether to show admin features. Test if a number is within range. Filter search results. Control loop execution. Every one of these requires answering yes/no questions in code.
Booleans are Python's data type for truth values—True or False. They're the foundation of every decision your program makes, powering if statements, while loops, data filtering, and conditional logic throughout your code.
What is a Boolean?
A boolean (bool type) represents one of two values: True or False:
- Booleans must be capitalized—
TrueandFalse, nottrue/false. Python will raiseNameErrorfor lowercase versions.
Most booleans aren't assigned directly—they're the result of comparisons, function returns, or logical operations:
| Booleans from Comparisons | |
|---|---|
- Comparison operators (
>=,==,!=, etc.) return boolean values - Evaluates to
Falsebecause 0 is not greater than 0
Why Booleans Matter
Booleans enable decision-making in code:
- Authentication: Is the user logged in? Do they have permission?
- Validation: Is the email valid? Is the form complete? Is the input within range?
- Control flow: Should the loop continue? Should this branch execute?
- Filtering: Does this item match criteria? Should it appear in results?
- State management: Is the connection active? Is data loaded? Is processing complete?
Without booleans, programs couldn't make decisions. Every if statement, every loop condition, every filter—all built on boolean logic.
Comparison Operators
Check if a score passes a threshold. Verify a password matches. Test if an age qualifies for a discount. Comparisons return boolean values that drive program logic:
| Comparison Operators | |
|---|---|
==tests equality—returnsFalse(10 does not equal 5)!=tests inequality—returnsTrue(10 is not equal to 5)>,<,>=,<=compare magnitude—work with numbers, strings, and other comparable types
These operators work with numbers, strings (alphabetical order), and other comparable types:
| Comparing Strings | |
|---|---|
- Returns
True—'a' comes before 'b' alphabetically - Returns
False—lowercase letters come after uppercase in ASCII/Unicode - Returns
True—string comparison is character-by-character: '1' < '9' in ASCII
String vs Number Comparison
Comparing strings that look like numbers can be surprising. "10" < "9" is True because
string comparison is character-by-character, and '1' comes before '9'. If you need
numeric comparison, convert to int or float first.
Chained Comparisons
Validate that a value falls within a range. Check if a date is between two bounds. Python lets you chain comparisons naturally:
| Chained Comparisons | |
|---|---|
- Returns
True—reads like mathematical notation: "is age between 18 and 65?" - Returns
True—multiple comparisons in one expression
Logical Operators
Require both username AND password. Grant access if admin OR moderator. Deny entry if NOT authenticated. Combining conditions is essential for complex logic—Python provides and, or, and not:
The and Operator
Both conditions must be True for the result to be True:
| The and Operator | |
|---|---|
- Both conditions must be true—age must be at least 16 AND license must exist
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
The or Operator
At least one condition must be True for the result to be True:
| The or Operator | |
|---|---|
- Only one condition needs to be true—either weekend OR holiday allows sleeping in
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
The not Operator
Flips True to False and vice versa:
| The not Operator | |
|---|---|
notinverts the boolean—not FalsebecomesTrue- Returns
True—twonotoperators cancel out
Combining Operators
Check complex eligibility. Validate multiple requirements. Build sophisticated filters—combine operators for precise logic:
- Multiple
orconditions—any one being true makes the whole expression true - Parentheses group conditions—must be adult AND (member OR ticket holder)
Use Parentheses for Clarity
While Python has operator precedence rules (not before and before or), explicit
parentheses make your intent clear and prevent bugs.
Truthiness: What Python Considers True or False
Check if a list has items without len(). Validate that a string isn't empty without comparison. Test for None in conditionals. Python's "truthiness" lets every value act as a boolean in context.
Falsy Values
These values are considered False when used in a boolean context:
| Falsy Values | |
|---|---|
Falseis obviously falsyNone(absence of value) is falsy—see None type- Zero in any numeric form (
0,0.0) is falsy - Empty string is falsy
- Empty collections (lists, dicts, sets, tuples) are falsy
Truthy Values
Everything else is considered True:
| Truthy Values | |
|---|---|
- Any non-zero number is truthy
- Negative numbers are truthy too!
- Non-empty strings are truthy
- String with just a space is truthy (not empty!)
- Non-empty collections are truthy
Why Truthiness Matters
Truthiness allows for elegant, Pythonic code:
- Verbose—explicitly checking length
- Pythonic—empty list is falsy, non-empty is truthy
- Pythonic—empty string is falsy
- Explicit None check—use when distinguishing None from other falsy values (0, "", etc.)
- Truthiness check—simpler but treats 0, "", [], etc. the same as None
Truthiness vs. Explicit Comparison
Be careful! if x: and if x == True: are different:
x = 1
print(x == True) # True — because bool(1) equals True
print(x is True) # False — 1 is not the same object as True
x = 2
print(x == True) # False — 2 doesn't equal True
print(bool(x)) # True — but 2 is still truthy!
When checking truthiness, use if x:. When checking for the actual boolean value,
use if x is True:.
Short-Circuit Evaluation
Skip expensive database queries. Avoid accessing attributes on None. Prevent unnecessary API calls. Python's "short-circuit evaluation" stops evaluating as soon as the result is known—boosting performance and safety:
How and Short-Circuits
With and, if the first value is falsy, Python doesn't bother checking the second:
| and Short-Circuiting | |
|---|---|
- This function would be expensive to run (database query, API call, etc.)
- Since
False and anythingis alwaysFalse, Python skips the function call entirely
How or Short-Circuits
With or, if the first value is truthy, Python doesn't bother checking the second:
| or Short-Circuiting | |
|---|---|
- Since
True or anythingis alwaysTrue, Python skips the function call
Practical Uses
Short-circuiting enables some elegant patterns:
| Short-Circuit Patterns | |
|---|---|
- Returns
Nonewithout crashing—ifuseris falsy, Python stops evaluating and returnsuser(None) - Use "Anonymous" if
input_nameis empty/None—theorpattern provides a default value - See functions for more on defining and using functions
- Short-circuits the rest of the function if items is empty/None—guard clauses prevent errors
The or Default Pattern
value or default is a common Python idiom for providing default values:
But be careful — this replaces any falsy value, including 0 or "" which might be
intentional. For more control, use value if value is not None else default.
The bool() Function
You can explicitly convert any value to a boolean using bool():
| Using bool() | |
|---|---|
- Returns
True—any non-zero number is truthy - Returns
False—empty string is falsy - Returns
True—non-empty list is truthy - Helpful debugging pattern to see both the value and its boolean interpretation
Practice Problems
Practice Problem 1: Comparison Operators
What does 5 < 10 < 15 evaluate to?
Answer
It returns True. This is a chained comparison that checks if 5 < 10 AND 10 < 15. Both conditions are true, so the entire expression is True. This is equivalent to 5 < 10 and 10 < 15, but more readable.
Practice Problem 2: Truthiness
Which of these values are truthy in Python: 0, [], " " (space), False, 1, None?
Answer
Only " " (string with a space) and 1 are truthy.
0is falsy (zero is always falsy)[]is falsy (empty list)" "is truthy (non-empty string—even just whitespace counts!)Falseis falsy (obviously)1is truthy (non-zero number)Noneis falsy (absence of value)
Practice Problem 3: Short-Circuit Evaluation
What will this code print?
Answer
It prints [1, 2, 3].
The or operator returns the first truthy value. Since [] (empty list) is falsy, Python evaluates the second operand [1, 2, 3], which is truthy, and returns it. This is the "default value" pattern: value or default.
Practice Problem 4: Logical Operators
What's the difference between == and is when comparing to True?
Answer
==checks for equality (value comparison)ischecks for identity (same object in memory)
x = 1
print(x == True) # True — 1 equals True in value
print(x is True) # False — 1 is not the same object as True
y = True
print(y == True) # True — obviously equal
print(y is True) # True — same object
For boolean checks, use if x: (truthiness) rather than if x == True: or if x is True: unless you specifically need to distinguish True from other truthy values.
Key Takeaways
| Concept | What to Remember |
|---|---|
| Values | Only True and False (capitalized!) |
| Comparison operators | ==, !=, <, >, <=, >= return booleans |
| Logical operators | and, or, not — can be combined |
| Falsy values | False, None, 0, 0.0, "", [], {}, () |
| Truthy values | Everything else |
| Short-circuit | and/or stop early when result is known |
| Pythonic style | Use if items: not if len(items) > 0: |
Further Reading
- Python Boolean Operations Documentation - Official reference for
and,or,not - Truth Value Testing - Complete list of falsy values and truthiness rules
- PEP 8 – Style Guide for Python Code - Boolean comparison best practices
- Computational Thinking - Understanding logical reasoning in programming
- Python Operators - Standard operators including comparison and boolean operators
Video Summary
Booleans are deceptively simple—just True and False—yet they're the foundation of every decision your program makes. Master comparison operators, logical combinations, and truthiness, and you control the flow of execution. Understand short-circuit evaluation, and you write safer, more efficient code.
Every if statement, every loop condition, every filter operation relies on boolean logic. The elegance of Python's truthiness (checking if items: instead of if len(items) > 0:) reflects the language's philosophy: explicit is better than implicit, but simple is better than complex. Booleans embody both principles—simple in concept, powerful in practice.