Python Booleans
Learn about Boolean values in Python and how to use them in conditional statements.
Boolean Values
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)When you run a condition in an if statement, Python returns True or False:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give you True or False in return.
Example
print(bool("Hello"))
print(bool(15))Example
x = "Hello"
y = 15
print(bool(x))
print(bool(y))Most Values are True
Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.
Example
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))Some Values are False
In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False.
Example
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))One more value, or object in this case, evaluates to False, and that is if you have an object that is made from a class with a __len__ function that returns 0 or False:
Example
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))Functions can Return a Boolean
You can create functions that returns a Boolean Value:
Example
def myFunction():
return True
print(myFunction())You can execute code based on the Boolean answer of a function:
Example
def myFunction():
return True
if myFunction():
print("YES!")
else:
print("NO!")Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type:
Example
x = 200
print(isinstance(x, int))Truthy and Falsy Values
Every object is either "truthy" or "falsy" in a boolean context (like an if). Memorize the short list of falsy values — everything else is truthy.
| Falsy | Truthy (examples) |
|---|---|
False, None | True |
0, 0.0 | any non-zero number |
"" empty string | "0", "False", any non-empty string |
[], {}, (), set() | any non-empty collection |
items = []
if items: # empty list is falsy
print("has items")
else:
print("empty") # this runsand / or Return Operands, Not Just True/False
Python's and/or short-circuit and return one of the operands — a useful idiom for defaults.
print(0 or "default") # default (0 is falsy)
print("hi" or "default") # hi
print("a" and "b") # b (both truthy -> last one)
name = user_name or "Guest" # fallback if user_name is emptyTry It Yourself
Exercise 1: Without running it, decide what bool("0") returns, then verify.
Show solution
print(bool("0")) # True -> non-empty string is truthyExercise 2: Use or to default an empty name to "Anonymous".
Show solution
name = ""
print(name or "Anonymous") # AnonymousKey Takeaways
- Booleans are
True/False; comparisons produce them. - Empty collections,
0,"", andNoneare falsy; almost everything else is truthy. and/orshort-circuit and return an operand — handy for defaults.
📘 Real-World Deep Dive
Every conditional in Python eventually reduces to a <code>bool</code>. Understanding truthy/falsy rules prevents "implicit <code>None</code>" bugs and lets you write concise guards.
Real-Life Scenario
Validating a payload from an external API — almost every key is <code>Optional</code>, and you want one tight guard.
Real-Life Example
from typing import Any
def looks_valid(p: dict[str, Any]) -> bool:
return bool(
p
and isinstance(p.get("id"), int)
and p["id"] >= 0
and p.get("email")
and "@" in p["email"]
and p.get("addresses") # non-empty list
)
samples = [
{"id": 1, "email": "a@b", "addresses": [{"city": "NY"}]},
{"id": -2,"email": "a@b", "addresses": [{"city": "NY"}]},
{"id": 3, "email": "", "addresses": [{"city": "NY"}]},
{"id": 4, "email": "a@b", "addresses": []},
None,
]
for s in samples:
print(f"{str(s)[:38]:<40} -> {looks_valid(s) if s else 'skipped'}")Expected Output
{'id': 1, 'email': 'a@b', 'addresses': [{'city -> True
{'id': -2, 'email': 'a@b', 'addresses': [{'city -> False
{'id': 3, 'email': '', 'addresses': [{'city': ' -> False
{'id': 4, 'email': 'a@b', 'addresses': []} -> False
None -> skippedCommon mistakes
if x:isFalseforxin["", 0, 0.0, [], {}, set(), None, False.x == Noneworks butx is Noneis the idiomatic check and is also slightly faster.return "found" if lst else "empty"differs fromreturn "found" if len(lst) else "empty"only in corner cases; pick deliberately.
🚀 Performance & Best Practices
- Short-circuit:
if cached_value and expensive_call(): ...avoids the cost ofexpensive_callwhen the cache is empty. - Truthiness on lists/dicts is O(1) — it's effectively a length check.
- Where bool must round-trip through JSON, cast explicitly:
bool(flag).
🧪 Try It Yourself
- Add a guard to
looks_validthat also requiresaddressesto be a non-empty list of dicts with a"city"key. - Replace the explicit
andchain with aall(...)over a list of predicates. - Write a one-liner that returns
"admin"only whenuser.is_admin and user.is_active and user.last_login > 0.