Ternary operator in Python (if ternary)

January 5, 2022

Ternary operator in Python (if ternary)

Ternary operator in Python was added in version 2.5 and it is a great resource, we will learn how to use it in this article.

Ternary operator in Python cover

Hey you programmer, okay? Let’s learn more about Python!

The normal “if” structure can sometimes take up too many lines, when we just need to run a little check.

So many programmers opt for the ternary conditional approach, which was added in Python version 2.5

Let’s see an example of the ternary if:

x = 2

print('success!') if x == 2 else print('fail!')

In this case the if was True, because the x is 2

The structure of the ternary if is as follows:

a if condition else b

“A” will be executed if a condition, which is the condition to be tested for is True

And “B” will be executed if a condition is False

Translating the first if into Python normal mode we have:

x = 2

if x == 2:
 print('deu certo')
 print('deu errado')

Note that we can save a lot of lines by going through the ternary operator option

Just be aware that inserting too much logic into the ternary can be a problem, as it confuses programmers and even you in the future

One-line code should only be used for very simple validations.

Otherwise opt for the normal version, your teammates will thank you


In this article we learned how to use the ternary operator in Python

Another important point is the way we use this operator, which should not be chosen if the logic to validate is very complex

It can make the code more confusing

Want to learn more about Python? If yes, click here!

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x