Ternary Operators in Python


Introduction

Python has support for shorthand if-else statements to save the number of lines of code. For the code that will consume 4 lines or even more than 4 lines, we can do the same only in a single line.

Shorthand If Else

The Shorthand if-else is used when we have only a single condition to evaluate. Based on that condition, we have to decide, either case A or case B.

Example: Here in this example, we will decide the bonus. If the rating is greater than 8, then the bonus is 100, else it is 20.

rating = 9 so bonus = 100

In [1]:
rating  = 9
salary = 5000

bonus = 100 if rating > 8 else 20
salary = salary + bonus

print(salary)
5100

rating = 7 so bonus = 20

In [2]:
rating  = 7
salary = 5000

bonus = 100 if rating > 8 else 20
salary = salary + bonus

print(salary)
5020

Shorthand Multiple If Else

We can use a new if else inside if else in a single line. Like this, it will work similar to if elif else statement. We can use as many if else inside existing if else as per the conditions.

Example: Here in this example, we will decide the bonus. If the rating is greater than 8, then the bonus is 100, else if the rating is greater than 6, then the bonus is 70 else it is 20.

rating = 9 so bonus = 100

In [1]:
rating = 9
salary = 5000

bonus = 100 if rating > 8 else 70 if rating > 6 else 20

salary = salary + bonus
print(salary)
5100

rating = 7 so bonus = 70

In [2]:
rating = 7
salary = 5000

bonus = 100 if rating > 8 else 70 if rating > 6 else 20

salary = salary + bonus
print(salary)
5070

rating = 5 so bonus = 20

In [3]:
rating = 5
salary = 5000

bonus = 100 if rating > 8 else 70 if rating > 6 else 20

salary = salary + bonus
print(salary)
5020