How to Use or to Fall Back to a Default Value in Python
A value from a form, a file or a setting is sometimes empty, and you want a sensible default in its place. Python's or does that in one expression: it gives you the first value, unless that value is empty, and then the second. This guide shows it with a display name, with real output from Python 3.15.2.
Syntax
<result> = <value> or <default>
| Part | What it means |
|---|---|
<value> | Used when it's true: not empty, not zero, not None |
<default> | Used when <value> is false |
The Python language reference: "The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned."
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
The script picks a display name twice: once when the saved name is empty, once when it holds Ada.
saved_name = ""
display_name = saved_name or "guest"
print(display_name)
saved_name = "Ada"
display_name = saved_name or "guest"
print(display_name)

Step 2: Run It
uv run python or_default.py
guest
Ada

The empty string is false, so the first or gave "guest". "Ada" is true, so the second gave "Ada".
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Using or when 0 is a real value | 0 is false too: volume or 10 gave 10 for a volume of 0 | volume if volume is not None else 10 gave 0 |
Expecting or to give True or False | It returns one of the two values themselves | Wrap it in bool(...) when you need True or False |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| A real value is replaced by the default | The value is one that counts as false, such as 0, 0.0, "" or [] | Test for None alone with is not None |
FAQ
Which values count as false?
In a check, None, "", 0, 0.0, [] and {} were all false, while the strings "0" and " " (a space) were true: any non-empty string is true.
Can I chain several fallbacks?
Yes. a or b or c gives the first value that's true, or c when none of them is.
Conclusion
saved_name or "guest" gave guest for an empty name and Ada for a real one. When 0 or another false value is valid, test for None instead.
Additional Resources
- Boolean operations — how
orandandchoose their result. - Truth value testing — which values count as false.
