Python Foundations for Data Work
Master core Python syntax and tooling for data tasks, from environments and notebooks to clean, reliable scripts.
Content
Booleans and Logic
Versions:
Watch & Learn
AI-discovered learning video
Sign in to watch the learning video for this topic.
Booleans and Logic — Python Foundations for Data Work
Remember when you compared numbers to find evens and glued text together with f-strings? Booleans are the tiny judges that gave you those True/False answers — now we learn how to make them work for data.
What is a Boolean (and why you actually care)
A Boolean is a value that can be either True or False. In Python the type is bool. That sounds tiny and boring, but booleans are the control center of programs and data workflows: they decide which rows to keep, which examples to label, and which branches of logic to run.
Where you already saw the idea:
- From the "Numbers and Arithmetic" lesson, comparisons like
x % 2 == 0produce a boolean. - From the "Strings and f-strings" lesson, you probably printed results like
f'{x} is even? {x % 2 == 0}'— that{...}was a boolean being formatted.
Booleans are the glue between raw data and decisions.
Core concepts
Boolean literals
is_raining = True
has_umbrella = False
print(type(is_raining)) # <class 'bool'>
Comparison operators (they produce booleans)
==,!=(equality / inequality)<,<=,>,>=(order comparisons)is,is not(identity — same object)
x = 7
print(x == 7) # True
print(x > 10) # False
print(x is 7) # usually True for small ints, but use == for equality checks
Micro explanation: use
==to compare values, useisonly when you care about identity (likeNonechecks:x is None).
Logical operators: and, or, not
and— True if both sides are Trueor— True if at least one side is Truenot— flips True/False
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
Important nuance: Python's and / or don't always return True/False; they return one of the operands (see short-circuiting section).
Truthiness: not just True/False
Many objects evaluate to True or False in boolean contexts. This is called truthiness.
Common falsy values:
None0,0.0''(empty string)[],(),{}(empty containers)False
Everything else is truthy.
| Value example | Boolean result |
|---|---|
0 |
False |
'' |
False |
[] |
False |
42, 'x' |
True |
if []:
print('this will not run')
else:
print('empty list is falsy')
Short-circuiting and the return-value trick
and and or evaluate left-to-right and stop as soon as the result is decided. But they return the actual operand they stopped on, not a boolean necessarily.
x and yreturnsxifxis falsy, otherwise returnsy.x or yreturnsxifxis truthy, otherwise returnsy.
This is super useful for default values:
name = ''
default = 'guest'
user = name or default
print(user) # 'guest'
# beware: if name can be '0' or 0 and that's meaningful, this trick may bite you
Booleans in arithmetic and data work
A cute and practical Python quirk: bool is a subclass of int. True == 1 and False == 0.
print(True + True + False) # 2
likes = [True, False, True]
print(sum(likes)) # 2 -> counts Trues
This is gold in data tasks: boolean masks let you count conditions quickly without loops.
# from prior lesson: numbers
values = [10, 3, 20, 0]
is_positive = [v > 0 for v in values]
print(is_positive) # [True, True, True, False]
print(sum(is_positive)) # 3 (how many positives)
In pandas / numpy you'll do the same with arrays and masks to filter rows.
Common pitfalls and gotchas
Equality vs identity: use
==for value equality. Useisonly for singletons likeNone.and/orreturn operands, not booleans. If you need a strict boolean, wrap withbool(...).
result = '' or 'fallback' # returns 'fallback'
print(bool(result)) # True
- Operator precedence:
not>and>or.
# same as: not (a and b) or c
- Chaining comparisons is elegant and Pythonic:
x = 5
print(0 < x < 10) # True (checks both at once)
- Floating point comparisons: avoid
==for floats that come from computation. Prefer tolerance checks.
Small real-world example: filtering data (pure Python)
Imagine a small dataset of users with ages and subscription status. Use booleans to filter.
users = [
{'name': 'Ada', 'age': 30, 'subscribed': True},
{'name': 'Ben', 'age': 17, 'subscribed': False},
{'name': 'Cleo', 'age': 22, 'subscribed': True},
]
# find adult subscribed users
adults_subscribed = [u for u in users if u['age'] >= 18 and u['subscribed']]
print([u['name'] for u in adults_subscribed]) # ['Ada', 'Cleo']
# count them
print(sum(u['age'] >= 18 and u['subscribed'] for u in users)) # 2
See how the boolean expression inside sum becomes 1 or 0? Nice and concise.
"This is the moment where the concept finally clicks." — when you realize booleans are tiny decision engines that convert comparisons into actions.
Quick exercises (do these out loud)
- Print whether 2024 is divisible by 4, and format it with an f-string:
f'2024 leap? {...}'. - Create a list of numbers and use a comprehension to count how many are negative.
- Try
'' or 0 or None or 'ok'and predict the result before running.
Key takeaways
- Booleans = True / False. They come from comparisons and control flow.
- Truthiness: many objects evaluate to True/False without being
TrueorFalseexplicitly. - Short-circuiting:
and/orcan return operands — useful for defaults. - Booleans are numbers (True==1), which makes counting conditions trivial.
Memorable insight: booleans are tiny but mighty — they turn your numerical and textual checks into decisions that shape every analysis pipeline.
Tags: beginner, python, data-science
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!