Ternary Operator

Ternary Operator OR Conditional Operator

Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5.

This operator simply allows to test a condition in a single line replacing the multi line if-else making the code compact.

Syntax

x = firstValue if condition else secondValue

If condition is True then firstValue will be considered else secondValue will be considered.

a,b=10,20
x=30 if a<b else 40
print(x)
30

E.g: Read two numbers from the keyboard and print minimum value

a=int(input("Enter First Number: "))
b=int(input("Enter Second Number: "))
min=a if a<b else b
print("Minimum Value:",min)

Output

Enter First Number: 10 
Enter Second Number: 30 
Minimum Value: 10

Ternary Operator
Scroll to top