Ternary or Conditional Operator in Python with Examples

Table of Contents

In other programming languages like C, C++, PHP, ... etc, we have conditional operator :? for making quick decision. But in python we don't use :? symbol for conditional operator. Conditional operator is also known as Ternary Operator.

Ternary Expression Syntax

Python uses following syntax for Conditional (Ternary) Operator:


a if condition else b

Where a and b are variables and condition is any valid entity in python which gives either True or False.

Ternary Example

Consider a following piece of code in python:


age = 22

if age>=18:
    print('You can vote.')
else:
    print('You can not vote.')

Above code can be written in one line using ternary or conditional operator, which looks like:


age = 22
print('You can vote.') if age>=18 else print('You can not vote.')

Why Ternary?

This structure i.e. <Expression1> if condition else <Expression2> in python is known as Ternary Operator. It is called ternary operator beacuse it takes three operand to work, namely, Expression1, Expression2 and Condition.