Ternary Operator in Python

By Hemanta Sundaray on 2021-08-19

In python, conditional expressions (aka ternary operator) help us conditionally assign a value based on the result of an expression.

Syntax

x if condition else y

If condition is true, x is evaluated and its value is returned; else y is evaluated and its value is returned.

Example:

country = "France"

greeting = "Bonjour" if country == "France" else "Good Morning"

print(greeting)
# Bonjour

Join the Newsletter