Ternary Operator

Python Ternary Operator is a concise syntax to select one of the values based on a condition.

The syntax of Python Ternary Operator is

</>
Copy
value1 if condition else value2

where value1 and value2 are the values from which one has to chosen, if and else are keywords, and condition is a boolean expression.

Example

In the following program, movie ticket pricing system, we write an expression with ternary operator to choose a value of 100 if age is greater than or equal to 18, or a value of 50 if age is less than 18.

Python Program

</>
Copy
age = int(input('Enter age : '))
price = 100 if age >= 18 else 50
print('Ticket Price :', price)

Output #1

Enter age : 24
Ticket Price : 100

Output #2

Enter age : 11
Ticket Price : 50

If we use if-else statement instead of Ternary Operator, the code would be as shown in the following.

Python Program

</>
Copy
age = int(input('Enter age : '))
price = 0
if age >= 18 :
    price = 100
else :
    price = 50
print('Ticket Price :', price)

Therefore, Ternary Operator is concise, and increases readability of code.

Conclusion

In this Python Tutorial, we learned the syntax of Ternary Operator, and how to use it to select one of the two values, with examples.