Understanding Truthy and Falsy
In programming, especially when dealing with conditional statements, values are evaluated as either truthy
or falsy
. These evaluations determine whether a block of code runs or is skipped. Truthy values act like true
, and falsy values act like false
in a conditional context.
Common Falsy Values
- 0 (zero)
- "" (empty string)
- null
- undefined
- false
- NaN (Not a Number)
Common Truthy Values
- Any non-zero number
- Non-empty strings (e.g., "hello")
- Non-empty collections (like arrays or objects)
- Boolean true
Example 1: Truthy in If Condition
value = "welcome"
if value:
print("Value is truthy")
else:
print("Value is falsy")
Output:
Value is truthy
Example 2: Falsy with Zero
count = 0
if count:
print("Count is truthy")
else:
print("Count is falsy")
Output:
Count is falsy
Why does this matter?
When writing conditions, knowing what values count as false can help prevent bugs. For example, accidentally treating an empty string or zero as valid data can cause unintended behavior.
Example 3: Using Collections
items = []
if items:
print("There are items")
else:
print("List is empty")
Output:
List is empty
Question:
What do you think happens when the variable contains an empty string?
Answer: An empty string is evaluated as falsy, so the else
block will run.
Example 4: Negating a Falsy Value
is_empty = ""
if not is_empty:
print("The variable is empty")
Output:
The variable is empty
Pro Tip:
When checking if a variable has a "real" value (i.e., not null, not zero, not empty), you can use the variable directly in a conditional. But be cautious: sometimes you want to differentiate between 0
(which is falsy) and something truly invalid like null
.
Summary
- Truthy and Falsy are concepts used in conditional logic.
- Falsy values include
0
,""
,null
,false
. - Everything else is considered truthy.
- These values control whether code in
if
,while
, etc., gets executed.
Mini Quiz
Q1: Is the number -1
truthy or falsy?
A: Truthy
Q2: What happens if you evaluate null
in a conditional?
A: It is falsy, so the conditional will treat it as false
.