Skip to main content

How to Use or to Fall Back to a Default Value in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<result> = <value> or <default>
PartWhat 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.

or_default.py
saved_name = ""
display_name = saved_name or "guest"
print(display_name)

saved_name = "Ada"
display_name = saved_name or "guest"
print(display_name)

The or_default.py script in a macOS-style code window: saved_name set to an empty string, display_name = saved_name or "guest", print, then the same with saved_name set to "Ada".

Step 2: Run It​

Terminal
uv run python or_default.py
Output
guest
Ada

The script's output in a terminal: guest, then Ada.

The empty string is false, so the first or gave "guest". "Ada" is true, so the second gave "Ada".

Common Mistakes​

MistakeWhat happensDo this instead
Using or when 0 is a real value0 is false too: volume or 10 gave 10 for a volume of 0volume if volume is not None else 10 gave 0
Expecting or to give True or FalseIt returns one of the two values themselvesWrap it in bool(...) when you need True or False

Troubleshooting​

SymptomLikely causeFix
A real value is replaced by the defaultThe 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​