Summary: in this tutorial, you’ll learn about the Python ternary operator and how to use it to make your code more concise.
Introduction to Python Ternary Operator #
The following program determines the ticket’s price based on the age of a person:
age = 19
if age >= 18:
ticket_price = 20
else:
ticket_price = 5
print(f"The ticket price is ${ticket_price}")
Code language: Python (python)
Output:
The ticket price is $20
Code language: Python (python)
In this example, the following if...else
statement set the ticket price to 20 if the age is greater than or equal 18 or 5 if otherwise:
if age >= 18:
ticket_price = 20
else:
ticket_price = 5
Code language: Python (python)
To make it more concise, you can use an alternative syntax of the if...else
statement like this:
ticket_price = 20 if age >= 18 else 5
Code language: Python (python)
In this statement, the left side of the assignment operator (=
) is the variable ticket_price
.
The expression on the right side returns 20 if the age
is greater than or equal to 18
or 5
otherwise.
Here’s the basic syntax of ternary operator in Python:
value_if_true if condition else value_if_false
Code language: Python (python)
The ternary operator evaluates the condition
. If the result is True
, it returns the value_if_true
. Otherwise, it returns the value_if_false
.
The ternary operator is equivalent to the following if...else
statement:
if condition:
value_if_true
else:
value_if_false
Code language: Python (python)
Note that you have been programming languages such as C# or Java, and you’re familiar with the following ternary operator syntax:
condition ? value_if_true : value_if_false
Code language: Python (python)
However, Python doesn’t support this kind of ternary operator syntax.
The following program uses the ternary operator instead of the if
statement:
age = 20
ticket_price = 20 if int(age) >= 18 else 5
print(f"The ticket price is ${ticket_price}")
Code language: Python (python)
The ticket price is $20
Summary #
- The Python ternary operator is
value_if_true if condition else value_if_false
. - Use the ternary operator to make your code more concise.