Ternary Operator in Python

This tutorial will teach you about the Python ternary operator and how to use it to make your code more concise.

The following program asks for your age and then calculates the ticket price:

age = input('Enter your age:')

if int(age) >= 18:
    ticket_price = 20
else:
    ticket_price = 5

print(f"The ticket price is {ticket_price}")

Here’s what happens if you type 18:

Enter your age:18
The ticket price is $20

If the age is more than or equal to 18, the following if…else line assigns 20 to the ticket price. Otherwise, the ticket price 5 is assigned:

if int(age) >= 18:
    ticket_price = 20
else:
    ticket_price = 5

You can use an alternate syntax like this to make it more concise:

ticket_price = 20 if int(age) >= 18 else 5

The variable ticket price is on the left side of the assignment operator (=) in this expression.

If the age is more than or equal to 18, the equation on the right side yields 20; otherwise, it returns 5.

In Python, a ternary operator has the following syntax:

value_if_true if condition else value_if_false

The condition is evaluated using the ternary operator. It returns value if true if the result is True. Otherwise, value if false is returned.

The following if…else sentence is equal to the ternary operator:

if condition:
    value_if_true
else:
    value_if_true

If you’ve worked with programming languages like C# or Java, you’ll recognise the following ternary operator syntax:

condition ? value_if_true : value_if_false

This ternary operator syntax, however, is not supported by Python.

Instead of the if statement, the following programme use the ternary operator:

age = input('Enter your age:')

ticket_price = 20 if int(age) >= 18 else 5

print(f"The ticket price is {ticket_price}")
%d bloggers like this: