Skip to content

Python Ternary Operator | conditional expressions

  • by

Python ternary operators 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.

Syntax

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.

a = 20

check = "true" if a == 20 else "false"

print(check)

Output: true

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:
    print('Kid')
elif age > 10 <= 20:
    print('Teen')    
elif age > 20:
    print('Adult')

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')

Output:

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading