The Secret Life of Python: Truthiness and Falsy Values
Source: Dev.to
The Soul of the Object
Margaret set her tea down. “Python isn’t lying, Timothy. It’s just being very… philosophical. To Python, an if statement doesn’t just ask if a variable exists. It asks if the variable has truthiness.”
Truthiness? Timothy asked. “Is that a technical term?”
“In Python, it absolutely is,” Margaret smiled. “Every object in this language has an inherent ‘truth’ or ‘lie’ inside it. Think of the if statement as a bouncer at a club. He doesn’t just check if you have a name; he checks if you’re bringing anything to the party. If you’re empty‑handed, you’re Falsy.”
The “Falsy” Hall of Fame
You can test any object’s truthiness with the bool() function:
bool(0) # False
bool(0.0) # False
bool("") # False
bool([]) # False
bool(()) # False
bool({}) # False
bool(None) # False
If any of these values appear in an if statement, they behave like False.
Note: Falsy values are not the same as the boolean
False.
0 == Falseevaluates toTruebecause they share a value, but0 is FalseisFalsebecause they are different objects.
The Lying Zero
Timothy tried changing the score to a string:
score = "0"
if score:
print(f"Current Score: {score}")
else:
print("Welcome! Please play a match to see your score.")
Output
Current Score: 0
A non‑empty string, even "0", is truthy. Even a string containing a single space—bool(" ")—is truthy.
Identity vs. Substance
To check for a score of zero without the “bouncer” rejecting it, test for identity rather than truthiness:
score = 0
# Don't ask 'if score' (truthiness)
# Ask 'if score is not None' (identity)
if score is not None:
print(f"Current Score: {score}")
else:
print("Welcome! Please play a match.")
Output
Current Score: 0
Using is not None asks Python whether the variable points to an actual object in memory, regardless of whether that object is 0, False, or an empty collection.
Margaret’s Cheat Sheet: The Lying Truth
- Truth Detector:
bool(x)– see how Python evaluates an object’s truthiness. - Shortcut (
if x:): Use when you only care whether a collection has items or a string has characters. - Professional’s Guard (
if x is not None:): Use when0,False, or empty containers are valid data you don’t want to skip. - String Trap:
"0","False"and" "are all truthy because they are not empty.
In the next episode, Margaret and Timothy will face “The Copy Cat”—where Timothy learns that sometimes making a copy of something creates a ghost that still haunts the original.