Use Python’s ternary conditional expression (true_value if condition else false_value) directly inside print(...) or inside an f-string placeholder (print(f"{'Yes' if ok else 'No'}")), always providing both if and else branches.
Basic Example
score = 85
items = 1
# 1. Recommended (standalone expression inside print):
print("Pass" if score >= 50 else "Fail")
# Output: Pass
# 2. Recommended (embedded inside an f-string for pluralization or status labels):
print(f"Found {items} {'file' if items == 1 else 'files'}.")
# Output: Found 1 file.
# 3. Parenthesize ternary expressions when combining with `+` or other operators:
print("Status: " + ("Active" if score > 0 else "Inactive"))
# Output: Status: Active
Key Details & Edge Cases
- Both
ifandelseare mandatory (SyntaxErrorifelseis omitted):- Unlike a multi-line
ifstatement, an inline conditional expression must always evaluate to a concrete value, so omittingelse(print("Pass" if score >= 50)) raisesSyntaxError: invalid syntax.
- Unlike a multi-line
- Operator precedence trap with
+,*, and comparisons:- The
if ... elseternary operator has lower precedence than almost every other Python operator (+,*,==,in,and,or). - Writing
print("Result: " + "Pass" if score >= 50 else "Fail")parses as("Result: Pass") if score >= 50 else "Fail"—dropping"Result: "on failure! Always wrap inline ternaries in parentheses("Pass" if score >= 50 else "Fail")when concatenating or performing arithmetic.
- The
- Lazy (short-circuit) evaluation:
- Only the chosen branch is evaluated at runtime (
a() if cond else b()never callsb()whencondis truthy), so side effects or division-by-zero in the unchosen branch (x / y if y != 0 else 0) are completely safe.
- Only the chosen branch is evaluated at runtime (
- Keep inline conditionals simple—avoid nested ternaries:
- Chaining multiple ternaries (
"A" if x > 90 else "B" if x > 80 else "C") quickly hurts readability. Move multi-branch logic into a helper variable,match/case, or dictionary lookup before callingprint().
- Chaining multiple ternaries (
- Avoid the legacy
cond and true_val or false_validiom:- Older code sometimes uses
print(cond and "Yes" or ""), which silently breaks whenevertrue_valitself is falsy (0,"",[],False). Always usetrue_val if cond else false_val.
- Older code sometimes uses
Comparison of Inline Conditional Patterns in print()
| Pattern | Syntax | Safe When True Branch Is 0 or ""? |
Handles Multi-Branch (elif) Cleanly? |
Best Used When |
|---|---|---|---|---|
| Ternary Expression (Recommended) | print("Yes" if ok else "No") |
Yes | No (avoid nesting) | Choosing between two values directly inside print(). |
| Ternary Inside f-String | print(f"{n} {'item' if n == 1 else 'items'}") |
Yes | No | Formatting plural nouns, signs, or inline status words inside larger text. |
| Tuple Indexing (Trick) | print(("No", "Yes")[bool(ok)]) |
Yes (eagerly evaluates both!) | No | Avoid—evaluates both branches unconditionally and obscures intent. |
Boolean and / or (Legacy) |
print(ok and "Yes" or "No") |
No (fails if true value is falsy) | No | Never—always replace with a if cond else b. |
You must log in or register to comment.