Skip to main content

How to Write an If-Else on One Line in Python with a Conditional Expression

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<value_if_true> if <condition> else <value_if_false>
PartWhat 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​

advice.py
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 advice.py script in a macOS-style code window: with temperature 31 a conditional expression picks Wear a hat or Bring a jacket, then the same expression runs inside print with temperature 12.

The first use stores the result in a variable; the second uses it directly as print()'s argument.

Step 2: Run It​

Terminal
uv run python advice.py
Output
Wear a hat
Bring a jacket

The output in a terminal: Wear a hat, then 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​

MistakeWhat happensDo this instead
Leaving out the else part, as in x = "a" if TrueSyntaxError: expected 'else' after 'if' expressionAlways give both values
Packing several conditions into one lineIt works, but it gets hard to readUse a normal if/elif/else statement

Troubleshooting​

SymptomLikely causeFix
The wrong value comes backThe condition is reversedRead 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​