Eiffel’s conditional expressions

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 = 10z = 1 + x if x == 1 else y   # 10
z = 1 + (x if x == 1 else y) # 11

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.