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 prompts you for your age and determines the ticket price based on it:
age = input('Enter your age:')
if int(age) >= 18:
ticket_price = 20
else:
ticket_price = 5
print(f"The ticket price is {ticket_price}")
Code language: Python (python)
Here is the output when you enter 18:
Enter your age:18
The ticket price is $20
Code language: Python (python)
In this example, the following if...else
statement assigns 20 to the ticket_price
if the age
is greater than or equal to 18. Otherwise, it assigns the ticket_price
5:
if int(age) >= 18:
ticket_price = 20
else:
ticket_price = 5
Code language: Python (python)
To make it more concise, you can use an alternative syntax like this:
ticket_price = 20 if int(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.
The following syntax is called a 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 ternary operator syntax.
The following program uses the ternary operator instead of the if
statement:
age = input('Enter your age:')
ticket_price = 20 if int(age) >= 18 else 5
print(f"The ticket price is {ticket_price}")
Code language: Python (python)
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.