Rams Poster
When Python checks a condition (the part after if, while, etc.) it needs to decide whether the statement is True or False.
You might think it only looks at the words True or False, but Python is a bit smarter – it treats many everyday values as “truthy” (meaning True) or “falsy” (meaning False) automatically.
What counts as falsy?
- 0 – the number zero
- 0.0 – zero as a float
- "" – an empty string, nothing between the quotes
- [] – an empty list, no items inside
- {} – an empty dictionary, no key‑value pairs
- set() – an empty set
- None – a special value that means “nothing here”
Everything else is considered truthy – even things you might not expect, like a non‑empty string "False" or a list with a single zero [0].
Why does this help?
Because you can write shorter, clearer code. Instead of checking the length of a list, you can just ask “does the list have something in it?”:
my_list = [] # try changing this to ['apple']
if my_list: # works because an empty list is falsy
print("We have items!")
else:
print("The list is empty.")
The same idea works for strings, numbers, and many other objects:
name = "" # try changing this to "Alice"
if name:
print(f"Hello, {name}!")
else:
print("You didn't type a name.")
A handy trick: use the or operator to give a default value when something is falsy.
user_input = "" # imagine the user pressed Enter without typing
# If user_input is falsy (empty), use "guest" instead
username = user_input or "guest"
print(f"Welcome, {username}!")
Here Python evaluates user_input. If it’s truthy, username gets that value; if it’s falsy, Python moves on to the right side of or and picks "guest".
Bottom line:
- Think of falsy as “empty or nothing”.
- Anything that isn’t falsy is truthy.
- Use this shortcut to write cleaner, more pythonic code that reads almost like plain English.
Happy coding! 🎉
9 ·