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.
Ternary Operator was added in python version 2.5.
a if condition else b
Let’s Understand Ternary Operator syntax:-
condition is evaluated, then exactly one of either
b is evaluated and returned based on the Boolean value of
condition evaluates to
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.
a = 20
check = "true" if a == 20 else "false"
Q: Does it possible Python ternary operator without else?
Answer: You can use the single line if syntax to do so.
if <condition>: <some-code>
Q: How to make Python ternary operator multiple conditions?
Answer: For example you want to turn this code into a shorthand line of code.
inpt = input('Age: ')
age = int(inpt)
if age <= 10:
elif age > 10 <= 20:
elif age > 20:
Let’s try the short-circuiting. But the above code is more readable.
age = int(input('Age: '))
print('Adult' if age > 20 else 'Kid' if age <= 10 else 'Teen')
Do comment if you have any doubts and questions.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.