Python Ternary Operator | conditional expressions

Python ternary operator or conditional expressions are used to evaluate something based on a condition being true or false. See the below The expression syntax of it.

Python Ternary Operator conditional expressions

 Ternary Operator was added in python version 2.5.


a if condition else b

Let’s Understand Ternary Operator syntax:-

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

Simple Ternary Operator example in Python

In the example, a variable has value and checking the condition if the value of a is 20 then print true else print false.

Output: true

Q: Does it possible Python ternary operator without else?

Answer: You can use the single line if syntax to do so.

Q: How to make Python ternary operator multiple conditions?

Answer: For example you want to turn this code into a shorthand line of code.

Let’s try the short-circuiting. But the above code is more readable.


Python multiple conditions operator

Do comment if you have any doubts and questions.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

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