Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Python’s ternary operator is officially called a conditional expression. It selects one of two values in a single expression:
value_if_true if condition else value_if_false
For example, status = "adult" if age >= 18 else "minor" evaluates age >= 18 first, then evaluates and returns only the selected value. This guide explains the syntax, evaluation order, precedence, nesting, practical patterns, and when a normal if/else statement is clearer.
Python ternary syntax at a glance
The complete form is:
value_if_true if condition else value_if_false
The true-result expression comes first, unlike the order used by a statement:
if condition:
value = value_if_true
else:
value = value_if_false
A conditional expression produces a value, so it can appear in an assignment, function argument, list, return statement, or another expression.
#1 Best Overall
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
print("pass" if score >= 60 else "fail")
Python’s Language Reference defines the behavior as: “The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.” See the Python 3.12 Language Reference, especially sections 6.13 and 6.17.
How evaluation works
The condition is evaluated first
Python checks the condition before either result expression. This matters when a branch calls a function, performs a calculation, or could raise an exception.
def get_name():
print("name branch ran")
return "Ada"
def get_guest():
print("guest branch ran")
return "Guest"
name = get_name() if logged_in else get_guest()
If logged_in is true, only get_name() runs. If it is false, only get_guest() runs. The unused branch is not evaluated.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Truth testing follows normal Python rules
The condition uses Python’s usual truth-value testing. Values such as False, None, 0, 0.0, empty strings, and empty collections are false; most other objects are true.
items = []
message = "Items available" if items else "Cart is empty"
Use an explicit comparison when the distinction matters. For example, "yes" if value is True else "no" is different from "yes" if value else "no".
Common patterns
Choose a label
price = 0
price_label = "free" if price == 0 else f"${price:.2f}"
print(price_label) # free
Provide a default
display_name = username if username else "Anonymous"
For a missing value only, rather than every false value, use an explicit is not None test:
Rank #2
label = supplied_label if supplied_label is not None else "Untitled"
Return one of two values
def sign(number):
return "positive" if number > 0 else "non-positive"
Use it inside another expression
total = subtotal + (shipping if expedited else 0)
print(f"{'Enabled' if feature_on else 'Disabled'}")
Pass a selected argument
send_email(to, priority="high" if urgent else "normal")
Conditional expressions versus if/else statements
Both forms can implement the same two-way choice, but they serve different readability needs.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstall| Situation | Prefer a conditional expression | Prefer a statement |
|---|---|---|
| Result | One short value is selected | Branches perform actions or assign several values |
| Number of choices | Exactly two outcomes | Several cases requiring elif |
| Length | Condition and both values fit clearly on one line | Logic spans lines or needs comments |
| Control flow | Expression is embedded in a larger expression | Early returns, loops, exceptions, or multiple statements are involved |
Equivalent code can look like this:
# Expression
price_label = "free" if price == 0 else f"${price:.2f}"
# Statement
if price == 0:
price_label = "free"
else:
price_label = f"${price:.2f}"
The language reference specifies semantics, not a universal style or speed advantage. Choose the form a reader can understand without mentally rearranging it.
Precedence and parentheses
Conditional expressions have very low precedence. Most operators bind more tightly, so a condition such as a + b > limit is read as expected. Parentheses are useful when combining a conditional expression with other operations or passing it where grouping is not obvious.
result = ("yes" if ready else "no") + "!"
value = 10 * (2 if double else 1)
Without parentheses, the conditional expression may become the larger expression than you intended. Add them whenever a line could be parsed in two plausible ways.
Nested ternary expressions
The expression after else may itself be a conditional expression:
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →label = "large" if n > 100 else "medium" if n > 10 else "small"
Conditional expressions associate from right to left, so this means:
label = "large" if n > 100 else ("medium" if n > 10 else "small")
Parentheses make the grouping explicit, but several nested choices quickly become difficult to scan. For three or more cases, write the equivalent statement:
if n > 100:
label = "large"
elif n > 10:
label = "medium"
else:
label = "small"
What you cannot write
There must be an else branch
A conditional expression always returns one of two values. This is invalid:
# SyntaxError
value = "ready" if is_ready
If you need to do something only when a condition is true, use a statement:
Recommended Free Tools
if is_ready:
start()
Do not confuse it with a statement-level if
The order is deliberately different:
- Expression:
true_value if condition else false_value - Statement:
if condition: ... else: ...
Do not hide side effects
Although function calls are legal in either branch, embedding mutations or complex operations in a dense one-liner can obscure what happens. Move multi-step work into a statement or named function.
Debugging and troubleshooting
SyntaxError near else
Check that the true value appears before if, that an else is present, and that the whole expression is on a syntactically valid line. The template is X if C else Y, not if C then X else Y.
Both branches seem to run
They should not. Look for function calls elsewhere, a separate statement that runs the same function, or logging performed while constructing the condition. Only the selected branch expression is evaluated by the conditional expression itself.
The wrong value is selected
Print or inspect the condition and verify truthiness. An empty list, string, or dictionary is false, while a non-empty one is true. Use explicit comparisons when truthiness is not your intended rule.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteA nested expression is confusing
Add parentheses to show grouping, or replace the expression with if/elif/else. This is a readability fix, not a change in Python’s evaluation model.
Unexpected precedence
Parenthesize the conditional expression before applying arithmetic, concatenation, comparisons, or function arguments. Then run a small test with representative true and false inputs.
Performance, safety, and maintainability
A conditional expression does not evaluate the unused branch, so expensive or failure-prone work placed there is skipped when that branch is not selected. That behavior can prevent unnecessary work, but it is not a blanket performance guarantee over a statement form; both compile to Python control flow and practical cost depends on the expressions themselves.
- Keep conditions short enough to read at a glance.
- Use parentheses around embedded conditional expressions.
- Do not rely on a branch for validation that must always happen; the unselected branch will not run.
- Use a statement when each branch contains multiple operations, logging, resource management, or error handling.
- Test both outcomes, including boundary values such as zero, empty input, and exactly-at-the-limit numbers.
Runnable examples
Command-line script
def classify_score(score):
return "pass" if score >= 60 else "fail"
for score in (59, 60, 100):
print(score, classify_score(score))
Save as ternary_demo.py and run python ternary_demo.py. The output is:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →59 fail
60 pass
100 pass
List comprehension
numbers = [1, 2, 3, 4]
parity = ["even" if number % 2 == 0 else "odd" for number in numbers]
print(parity) # ['odd', 'even', 'odd', 'even']
Do not confuse the expression’s if/else with a comprehension filter, which has no else and appears after the loop.
Best Value
Or skip the browser setup
If your Python workflow needs a screenshot of a URL rather than a lesson in browser automation, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
Python:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
See the ScreenshotNeo API documentation for all options, including PNG, JPEG, WebP, PDF, device presets, custom CSS and JavaScript, selectors, waits, headers, cookies, geolocation, caching, signed links, asynchronous jobs, webhooks, and bulk capture.
Equivalent cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Equivalent Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Quick decision checklist
- Choose a conditional expression for one short, obvious value choice.
- Write the true value before
if, then the condition,else, and false value. - Remember that Python evaluates the condition first and only the selected branch.
- Add parentheses when precedence or nesting could slow comprehension.
- Use a regular statement for multi-step work or several alternatives.
Frequently Asked Questions
Is Python’s ternary operator called something else?
Yes. Python’s official terminology is “conditional expression”; “ternary operator” is the common informal name.
Can each branch return a different type?
Yes. Python returns whichever branch is selected, regardless of the other branch’s type; your program should still ensure that downstream code can handle the result.
Does a conditional expression require Python 3?
No. This syntax is part of modern Python and is available in supported Python 2 and all Python 3 versions, although current projects should use a supported Python 3 release.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

