Does Python Have a Ternary Conditional Operator?

Python’s short-hand method for writing an if/else statement

Jonathan Hsu
Oct 14 · 2 min read
Photo by Dil on Unsplash

The short answer is yes.

The ternary conditional operator is a short-hand method for writing an if/else statement. There are three components to the ternary operator: the expression/condition, the positive value, and the negative value.

The ternary operator is traditionally expressed using the question mark and colon organized as expression ? positive value : negative value

When the expression evaluates to true, the positive value is used—otherwise the negative value is used.

Python does not follow the same syntax as previous languages; however, the technique does exist. In Python, the components are reorganized and the keywords if and else are used, which reads positive value if expression else negative value

Given the Python syntax, the ternary operator is converted as follows:

# Traditional Ternary Operator
can_vote = (age >= 18) true : false;
# Python Ternary Operator
can_vote = True if age >= 18 else False

Keep in mind that the purpose of the ternary operator is to write more concise code, improving readability. However, the Python implementation may produce the opposite effect, being confusing to read. Additionally, the lack of explicit operators can lead to order of operations discrepancies.

x = 5
y = 10
z = 1 + x if x == 1 else y # 10
z = 1 + (x if x == 1 else y) # 11

Better Programming

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade