Placement Prep

Python Ternary Operator: One-Line if-else with Examples

Python's ternary operator compresses if-else into one line. Learn the syntax, practical examples, nested chaining, and when to stick with if-elif instead.

By FACE Prep Team 5 min read
python ternary-operator conditional-expression if-else beginners placement-prep programming

Python’s ternary operator compresses a two-branch if-else into a single line: value_if_true if condition else value_if_false. The condition sits in the middle.

What the Ternary Operator Does

Python’s conditional expression (the formal name for what most people call the ternary operator) evaluates a condition and returns one of two values. The equivalent four-line if-else block does the same thing.

Compare the two forms:

# Four-line if-else
if condition:
    result = value_if_true
else:
    result = value_if_false

# One-line ternary
result = value_if_true if condition else value_if_false

Three things to know about the syntax before the examples:

  • The condition goes in the middle, not at the start. This is the opposite of C and Java’s condition ? a : b form.
  • Both branches are full Python expressions. You can call functions, index lists, or do arithmetic on either side.
  • The result is an expression, not a statement. It can appear anywhere Python expects a value: an assignment, a function argument, a list element, or a return statement.

PEP 308, accepted for Python 2.5, added this syntax to the language. Before that, Python had no dedicated one-line conditional form.

Practical Examples

Pass or Fail

score = 72
result = "Pass" if score >= 50 else "Fail"
print(result)  # Pass

The variable result gets the string "Pass" because score >= 50 evaluates to True. If score were 40, result would be "Fail".

This pattern appears in placement coding questions that ask you to classify a number: pass or fail, even or odd, positive or negative. The ternary form is one line; the equivalent if-else is four. Both are correct; which to write depends on what the question specifies.

Even or Odd

num = 7
parity = "Even" if num % 2 == 0 else "Odd"
print(parity)  # Odd

The condition num % 2 == 0 sits inside the ternary without extra parentheses. Parentheses are optional but add clarity when the condition involves multiple operators.

Default Value

name = input("Enter name: ").strip()
display = name if name else "Anonymous"
print(display)

An empty string is falsy in Python, so name if name is a compact guard for blank input. No comparison operator is needed when testing truthiness directly.

Inside a Function Argument

score = 65
print("Above average" if score > 60 else "Below average")

The ternary expression evaluates before print() receives its argument. No intermediate variable is needed.

The greatest of two numbers article covers the ternary as one of four methods for finding the larger value. The form a if a >= b else b appears directly in placement multiple-choice questions and is worth knowing by itself.

When to Use It (and When Not To)

Use the ternary operator when:

  • You have exactly two outcomes and the condition is simple.
  • You are assigning a value based on a condition inside a list comprehension — for example, [x.upper() if x.isalpha() else x for x in chars] keeps each transformation on one line without a nested loop.
  • The full expression fits within one readable line.

Avoid it when:

  • Either branch involves a function call with side effects such as file writes or network calls.
  • The condition combines three or more comparisons.
  • The line length makes it hard to scan.

A poorly readable ternary:

label = "High" if score >= 90 and level == "advanced" and attempts <= 3 else "Low"

The cleaner equivalent:

if score >= 90 and level == "advanced" and attempts <= 3:
    label = "High"
else:
    label = "Low"

Both do the same thing. The if-else block is easier to read and debug.

Nested and Chained Conditions

Python allows chaining ternary expressions to cover more than two outcomes:

score = 78
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "F"

Python evaluates this left to right. If score >= 90 is False, it checks score >= 80, and so on until one condition is True or the final else is reached.

For two conditions the chain is still readable. For three or more, an if-elif chain is cleaner and easier to extend:

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

The greatest of three numbers in Python is a practical case where a nested ternary technically works but an if-elif block is cleaner. The readability boundary for nested ternaries is roughly two conditions.

If a coding platform’s expected style is unknown, the if-elif block is the safer default. It expresses the same logic but is easier to debug step by step, easier to extend with a new branch, and easier for a reviewer to follow at a glance.

Other One-Line Patterns

Three alternative patterns appear in older tutorials and placement question banks. Knowing what they do is enough; rarely write them in new code.

Tuple Form

result = ("Fail", "Pass")[score >= 50]

A boolean has integer values in Python: False is 0, True is 1. This indexes the tuple at position 0 or 1. The order is counterintuitive (the false value comes first), and both strings are always created in memory regardless of the condition.

This last point matters when either branch calls a function rather than returns a literal. The tuple and dict forms evaluate both expressions before indexing, so both functions run. The standard ternary evaluates only the branch that matches the condition.

Dictionary Form

result = {True: "Pass", False: "Fail"}[score >= 50]

Same idea, using a dict lookup. Verbose and no faster than the standard ternary.

Lambda Form

result = (lambda x: "Even" if x % 2 == 0 else "Odd")(num)

Wraps a ternary in an immediately-called lambda. Demonstrates that functions can return conditional expressions, but adds no practical benefit for this use case.

The standard value_if_true if condition else value_if_false is simpler and more readable than all three patterns. Placement questions sometimes ask you to trace the output of the tuple or dict form; knowing the indexing logic is the required skill.

For more programs that combine conditional logic with loops and functions, see the Python basic programs collection. The Python calculator program applies the same if-elif structure to a multi-operation problem, showing how conditional branching scales past two outcomes.


One-line conditionals show up constantly in Python once they click: setting defaults, selecting output strings, filtering list elements. The same if condition else pattern scales into LLM-facing code, where you might route a prompt based on user input or select between two response formats based on a model’s output length. TinkerLLM is a ₹299 Python environment where those patterns run on actual API calls, not toy examples.

Primary sources

Frequently asked questions

Does Python have a ?: operator like C or Java?

No. Python uses the if-else expression syntax: value_if_true if condition else value_if_false. PEP 308, accepted for Python 2.5, introduced this form as the language's conditional expression.

Can the ternary operator replace all if-else statements?

No. The ternary operator is an expression that must produce a value. An if-else block can execute statements like print, loops, or file I/O. Use ternary for inline conditional values; use if-else when branches contain statements rather than expressions.

Can I use the ternary operator inside a list comprehension?

Yes. The pattern [x if x > 0 else 0 for x in numbers] is valid Python. The ternary applies to each element as the comprehension iterates, replacing a nested if-else inside the loop.

Does nesting ternary operators affect performance?

No measurable performance difference exists between a ternary and the equivalent if-else block in CPython. The concern with nested ternaries is readability, not speed. At three or more conditions, an if-elif chain is easier to scan and debug.

What does a if a > b else b return when a equals b?

It returns b. The condition a > b is False when both values are equal, so the else branch evaluates. To return a when both are equal, change > to >= in the condition.

Is the ternary operator considered good Python style?

Yes, for simple two-branch assignments. Python's PEP 8 does not ban it. The convention is to keep ternary expressions short — if the logic involves more than two branches, an if-elif block is preferred.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF