Python ternary operator syntax: value if true, if condition, else value if false, with a nest status example

Python Ternary Operator: How to Write If Else in One Line (With Examples)

Lesson 8 of 16 in Python for Biologists, a free beginner course with ecology examples.

In lesson 7 you wrote decisions with if and else. Many of those decisions are tiny: is the nest occupied or empty, is the bird an adult or a juvenile, does the label say “nest” or “nests”? Writing four lines for a choice between two words feels like overkill. The ternary operator lets you write that kind of decision in a single, readable line.

Quick answer: The Python ternary operator (officially a conditional expression) picks one of two values based on a condition: value_if_true if condition else value_if_false. For example, status = "occupied" if eggs > 0 else "empty". The else part is required. Use it for short, simple choices between two values, and keep a normal if statement for anything longer.

Python ternary operator syntax: value if true, if condition, else value if false, with a nest status example
The three parts of a ternary, read left to right. Image: Erzsebet Frey

What You Will Learn in This Lesson

  • What the ternary operator is and how to read it
  • How to turn a four line if else into one line
  • Where ternaries are most useful: variables, f strings and plurals
  • How to handle three outcomes, and why you usually should not
  • When a normal if statement is the better choice

What Is the Ternary Operator in Python?

It is a short way to write an if else that produces a value. “Ternary” means it has three parts: the value when the condition is true, the condition, and the value when it is false.

Here is a nest check written the long way:

eggs = 3

if eggs > 0:
    status = "occupied"
else:
    status = "empty"

print(status)

And the same decision with the ternary operator:

eggs = 3
status = "occupied" if eggs > 0 else "empty"
print(status)   # occupied

Both versions do exactly the same thing. The second is simply shorter, and for a choice this small, easier to scan.

What Is the Syntax of the Python Ternary Operator?

value_if_true if condition else value_if_false

The order surprises people who know other languages, because the condition sits in the middle. Read it like an English sentence: “occupied if there are eggs, else empty.”

  • Python checks the condition first.
  • If it is True, the whole expression becomes the value on the left.
  • If it is False, it becomes the value on the right.

The condition can use any comparison or logical operator from lesson 5:

water_temp_c = 14
depth_cm = 35
pond = "suitable" if water_temp_c >= 10 and depth_cm >= 30 else "unsuitable"
print(pond)   # suitable

Can I Write a Ternary Without else?

No. A ternary must always produce a value, so both outcomes are required. Leave out else and Python stops:

status = "occupied" if eggs > 0
SyntaxError: expected 'else' after 'if' expression

If you only want something to happen when the condition is true, use a normal if statement.

Where Is the Ternary Operator Most Useful?

1. Choosing a Value for a Variable

This is the classic use. Ringers age birds, and a simple age class needs only one line:

age_years = 2
age_class = "adult" if age_years >= 1 else "juvenile"
print(age_class)   # adult

2. Getting Plurals Right

Nothing looks sloppier in a report than “1 nests”. A ternary fixes it neatly:

count = 1
word = "nest" if count == 1 else "nests"
print(f"Found: {count} {word}")   # Found: 1 nest

3. Inside an f String or print()

Because a ternary is an expression, you can drop it straight into an f string:

sample_size = 120
print(f"Sample: {'large' if sample_size > 100 else 'small'}")   # Sample: large

Note the single quotation marks inside the double ones, as you learned in lesson 6. Use this inline style only for very short choices. If the line gets long, store the result in a variable first.

Choose a Value, Not an Action

You will sometimes see code like this, including in some course materials:

temp_c = 10
print("Wear a jacket.") if temp_c < 15 else print("No jacket needed.")

It runs, but it uses the ternary to choose between two actions, which is not what it is for. Let the ternary choose the value, and call print() once:

temp_c = 10
print("Wear a jacket." if temp_c < 15 else "No jacket needed.")

Shorter, clearer, and it shows the real decision: which message to print.

Pinterest graphic: Python ternary operator cheat sheet, if else in one line with syntax and rules
The ternary rules on one pin. Image: Erzsebet Frey

Can a Ternary Handle Three Outcomes?

Yes, by putting a second ternary in the else part. Is a temperature change positive, zero or negative?

change = -0.4
trend = "warming" if change > 0 else "no change" if change == 0 else "cooling"
print(trend)   # cooling

Python reads it from left to right: if change > 0, the answer is “warming”. Otherwise it moves on to the second ternary. It works, but it is already harder to read than this:

change = -0.4

if change > 0:
    trend = "warming"
elif change == 0:
    trend = "no change"
else:
    trend = "cooling"

print(trend)   # cooling

A good rule: one ternary per line, two outcomes per ternary. Three or more outcomes belong in an if, elif, else chain.

When to use the Python ternary operator versus an if else statement: two simple values versus several outcomes or actions
A quick guide to choosing between the two. Image: Erzsebet Frey

When Should I Not Use the Ternary Operator?

Use a normal if statement when:

  • there are more than two outcomes;
  • each outcome needs more than one action, such as printing, counting and saving;
  • the condition is long and the line would scroll off the screen;
  • you only need something to happen in one case (no else).

Is the Ternary Operator Faster Than if else?

No. It is only shorter. Python turns both versions into practically the same instructions, so the speed is the same. Choose the ternary for readability, never for speed.

The Python reference calls this feature a conditional expression. If you are curious why the syntax looks the way it does, PEP 308 records the long debate that led to it.

Practice Tasks

Task 1: Treatment or Control

In a field experiment, even numbered plots get the treatment and odd numbered plots are controls. Read a plot number and use a ternary operator to print treatment or control.

Show the solution
plot = int(input("Plot number: "))
print("treatment" if plot % 2 == 0 else "control")

A number is even when the remainder after dividing by 2 is 0, the modulo trick from lesson 5.

Task 2: Population Trend

Read the change in a population count since last year (it can be negative or a decimal, for example an index change) and use ternary operators to print increased, no change or decreased. Then write the same program with if, elif and else, and decide which you prefer.

Show the solution
change = float(input("Change since last year: "))
print("increased" if change > 0
      else "no change" if change == 0
      else "decreased")

Splitting a long ternary over lines inside the brackets is allowed and keeps it readable. The if elif else version:

change = float(input("Change since last year: "))

if change > 0:
    print("increased")
elif change == 0:
    print("no change")
else:
    print("decreased")

Most people find the second version clearer, which is exactly the point of this task.

Task 3: Rewrite With a Ternary

Members of a field society get 10% off a field guide. Rewrite this code with a ternary operator.

status = "member"
if status == "member":
    discount = 10
else:
    discount = 0
print(f"Discount: {discount}%")
Show the solution
status = "member"
discount = 10 if status == "member" else 0
print(f"Discount: {discount}%")   # Discount: 10%

Task 4: Age Class From Input

Ask for a bird’s age in years (it can be a decimal, like 0.5) and print adult for 1 year or older and juvenile otherwise, using one ternary.

Show the solution
age_years = float(input("Age in years: "))
age_class = "adult" if age_years >= 1 else "juvenile"
print(f"Age class: {age_class}")

Task 5: Right Word, Right Number

Ask how many eggs are in a clutch and print a sentence like The clutch has 1 egg. or The clutch has 4 eggs.

Show the solution
eggs = int(input("Number of eggs: "))
word = "egg" if eggs == 1 else "eggs"
print(f"The clutch has {eggs} {word}.")

What does it print for 0? The clutch has 0 eggs., which is correct English, so the condition eggs == 1 is the right one.

Task 6: Ternary or Not?

Should this code be rewritten as a ternary? Explain why or why not.

weather = "cloudy"
temp_c = 10

if weather == "sunny" and temp_c > 25:
    advice = "Sun hat and light clothes."
elif weather == "rain" or temp_c < 15:
    advice = "Waterproofs and a warm layer."
else:
    advice = "Enjoy the cloudy day."

print(advice)
Show the solution

No. There are three outcomes and two combined conditions. A chained ternary would be one very long line that is hard to read and easy to break. The if elif else version is the right tool. (With these values it prints Waterproofs and a warm layer., because 10 is below 15.)

Task 7: Predict the Output

nests_a = 7
nests_b = 12
print("Site A" if nests_a > nests_b else "Site B")
print(nests_a if nests_a % 2 == 0 else nests_a + 1)
print("busy" if nests_a + nests_b > 15 else "quiet")
change = 0
print("increase" if change > 0 else "stable" if change == 0 else "decline")
Show the solution

Site B, 8, busy, stable. Note the second line: the values do not have to be text. A ternary can return numbers or calculations too, here rounding 7 nest boxes up to an even number for pairs of boxes.

Quiz: Python Ternary Operator

1. Which line is a correct Python ternary?
a) x = eggs > 0 ? "yes" : "no"   b) x = "yes" if eggs > 0 else "no"   c) x = if eggs > 0 "yes" else "no"

Show answer

b) The ? : form in a) is used in languages like C and JavaScript, not Python.

2. Where does the condition go?
a) first   b) in the middle   c) last

Show answer

b) in the middle, between if and else.

3. What happens if you leave out else?
a) the value becomes None   b) SyntaxError   c) nothing

Show answer

b) SyntaxError: expected ‘else’ after ‘if’ expression.

4. count = 1. What is "nest" if count == 1 else "nests"?
a) nest   b) nests

Show answer

a) nest

5. Is a ternary faster than the same if else statement?
a) yes, much faster   b) no, the speed is practically the same

Show answer

b) It is shorter, not faster.

6. For four possible outcomes, what should you use?
a) a chain of three ternaries   b) if, elif and else

Show answer

b) It is far easier to read and to change later.

7. What does print(5 if 3 > 4 else 9) show?
a) 5   b) 9   c) True

Show answer

b) 9, because 3 > 4 is false.

8. Which is better style?
a) print("cold") if t < 5 else print("mild")   b) print("cold" if t < 5 else "mild")

Show answer

b) Let the ternary choose the value and call print() once.

Key Takeaways

  • The ternary operator is value_if_true if condition else value_if_false.
  • It chooses a value. Use it in assignments, f strings and print().
  • The else part is always required.
  • It is shorter than if else, not faster.
  • Keep it to two outcomes. For three or more, use if, elif, else.

Previous lesson: Python If Else, Elif and Nested If
Next lesson: Python while Loop.
Back to the course: Python for Biologists, all 16 lessons

Share this

From the shop

Gifts for people who love the wild

Wildlife themed t-shirts, notebooks, tote bags, bandanas and guides, designed by an ecologist.

Visit the shop
Shopping Cart