Ternary conditional operator in Python

Last Updated On Friday 8th Oct 2021

Python Ternary

The ternary operator is an operator that takes three arguments.

Ternary Operator Python

  • The first argument is a comparison argument.
  • The second is the result of a true comparison.
  • The third is the result of a false comparison.
	a if condition else b
	

Conditional expressions are generally used to set values according to conditions. Also called the ternary operator. The ternary operator is shortened way of writing an if-else statement.

Ternary Operator

Python Conditional Operator

	true if <condition> else false
	
  • condition: This is a boolean condition that evaluates to either true or false.
  • true: The value returned by the ternary operator if the condition evaluates to True.
  • false: The value returned by the ternary operator if the condition evaluates to False.

The ternary operator differs from a standard if, else, elif structure because it is not a control flow structure and behaves more like other operators such as == or != in the Python language.

Example 1

	for val in range(1, 11):
    is_even = "Even" if val % 2 == 0 else "Odd"
    print(val, is_even, sep=' = ')
	

Output

	1 = Odd
2 = Even
3 = Odd
4 = Even
5 = Odd
6 = Even
7 = Odd
8 = Even
9 = Odd
10 = Even

	

Example 2

	rank = 222
num = 0.1 if rank > 111 else 0
print("rank:", rank, "  num:", num)
	
	# rank: 222   num: 0.1
	
  • The Python ternary operator is a more efficient way of performing simple if statements.
  • The ternary operator evaluates a condition, then returns a specific value depending on whether that condition is equal to True or False.