How to Write an If-Else on One Line in Python with a Conditional Expression
Choosing between two values with a full if/else statement takes four lines. A conditional expression, sometimes called Python's ternary operator, does it in one, and fits anywhere a value does: in an assignment, a print() or an argument. This guide shows it with two temperatures, with real output from Python 3.15.2.
Syntax
<value_if_true> if <condition> else <value_if_false>
| Part | What it means |
|---|---|
<condition> | Checked first |
<value_if_true> | The result when the condition is true |
<value_if_false> | The result otherwise. The else part is required |
Python's language reference: "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."
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
temperature = 31
advice = "Wear a hat" if temperature > 25 else "Bring a jacket"
print(advice)
temperature = 12
print("Wear a hat" if temperature > 25 else "Bring a jacket")

The first use stores the result in a variable; the second uses it directly as print()'s argument.
Step 2: Run It
uv run python advice.py
Wear a hat
Bring a jacket

At 31 degrees the condition temperature > 25 was true, so the first value came back; at 12 it was false, so the value after else did.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the else part, as in x = "a" if True | SyntaxError: expected 'else' after 'if' expression | Always give both values |
| Packing several conditions into one line | It works, but it gets hard to read | Use a normal if/elif/else statement |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| The wrong value comes back | The condition is reversed | Read it aloud: "this, if the condition holds, else that" |
FAQ
Is this the same as an if statement?
It gives the same choice, but it's an expression: it produces a value. An if statement runs blocks of code and produces nothing.
Is the value that isn't chosen computed?
No. Only the value the condition selects is evaluated.
Conclusion
"Wear a hat" if temperature > 25 else "Bring a jacket" gave Wear a hat at 31 degrees and Bring a jacket at 12, in one line each time.
Additional Resources
- Conditional expressions — how
x if C else yis evaluated.
