In this tutorial, we will discuss how to use the python ternary operator to make decisions.
You most likely already make use of python’s conditional statements to execute statements based on one or more conditions.
However, python also provides a way to select values based on a condition.
Using Python Conditional Statements for Program Flow
The following example code determines the unit price of t-shirts based on the number of t-shirts.
qty_tshirts = 11
if qty_tshirts <= 10:
unit_price = 10.50
else:
unit_price = 8.75
print(f"unit price is ${unit_price}")
Output:
unit price is $8.75
The code makes use of a conditional statement to decide what value to assign to unit_price
. If qty_tshirts
is less than or equal to 10, unit_price
should be $10.50
, otherwise unit_price
should be $8.75
.
The output shows that unit_price
was $8.75
because the value of qty_tshirts
was 11 (greater than 10).
We can write the whole if statement as an expression that returns a value based on a decision. To do this, we will make use of python’s ternary operator.
Python Ternary Operator
Python provides a conditional operator that could help us rewrite the previous conditional statement as a single expression.
This conditional operator is called a ternary operator because it requires three operands (unary operator – one operand, binary operator – two operands, ternary operator – three operands).
Python’s ternary operator has the following syntax:
value_if_true if condition else value_if_false
where:
value_if_true
will be returned when the condition evaluates toTrue
value_if_false
is the value the operator returns when the condition evaluates toFalse
condition
is a boolean expression that evaluates to eitherTrue
orFalse
Armed with python’s ternary if operator, the previous example could be made more concise as shown in the next example
qty_tshirts = 11
unit_price = 10.50 if qty_tshirts <= 10 else 8.75
print(f"unit price is ${unit_price}")
Output:
unit price is $8.75
We made the ternary expression part of an assignment statement. In that way, when the ternary expression returns a result, the result will be stored in the variable on the left hand of the assignment.
Nested Decisions Using Python Ternary Operator
The following code shows an example of a nested if statement
number = 10
if number < 0:
number_sign = "negative"
else:
if number == 0:
number_sign = "nothing"
else:
number_sign = "positive"
print(f"sign of {number} is {number_sign}")
The code wants to print out a message based on the sign of number
. If number < 0
, number_sign
should be assigned the value "negative"
, otherwise, if number == 0
, number_sign
should be assigned "nothing"
. Otherwise, we are left with the remaining possibility; number > 0
, which will result in number_sign
being assigned a value of "positive"
.
Since number
was equal to 10, our output would be
Output:
sign of 10 is positive
We can rewrite this nested if statement using a ternary operation in an assignment statement
number = 10
number_sign = "negative" if (number < 0) else ("nothing" if (number == 0) else "positive")
print(f"sign of {number} is {number_sign}")
Output:
sign of 10 is positive
The output is the same as the one produced using the nested conditional statements, but with fewer lines of code.
We can try to test the previous code by changing the value of number
to 0
number = 0
number_sign = "negative" if (number < 0) else ("nothing" if (number == 0) else "positive")
print(f"sign of {number} is {number_sign}")
Output:
sign of 0 is nothing
The next code changes the value of number
to -5:
number = -5
number_sign = "negative" if (number < 0) else ("nothing" if (number == 0) else "positive")
print(f"sign of {number} is {number_sign}")
Output:
sign of 0 is negative
More Complex examples of Python Ternary Operator
In the following examples, we will show how to use nested ternary operators to write more complex, nested ternary expressions.
Converting scores to grades using the Python Ternary operator
The next example converts scores into grades.
scores = [56, 45, 97, 23, 78, 61]
for score in scores:
grade = "A" if (score >= 90) else ("B" if (score >= 70)
else ("C" if (score >= 60)
else ("D" if (score >= 50)
else ("E" if (score >= 40)
else "F"))))
print(f"score: {score}, grade: {grade}")
The example displays grades for each score in a list. We used a set of nested ternary operators to help decide what grade to give a score. When we run this program, we will see the following printout
Output:
score: 56, grade: D
score: 45, grade: E
score: 97, grade: A
score: 23, grade: F
score: 78, grade: B
score: 61, grade: C
Classify animals by features with the Ternary operator
In this example, we have four animals we want to classify based on three features; whether it has feathers, whether it can fly, and whether it has fins. The program first defines a function that helps us construct and define an animal. The function animal()
returns a dictionary describing an animal with three features.
def animal(has_feathers=False, can_fly=False, has_fins=False):
# define an animal with three features
return {"has_feathers": has_feathers,
"can_fly": can_fly,
"has_fins": has_fins}
animals = [animal(has_feathers=True, can_fly=True),
animal(has_feathers=True, can_fly=False),
animal(has_feathers=False, has_fins=True),
animal(has_feathers=False, has_fins=False)]
for animal in animals:
# use a nested ternary to classify the animal
animal_species = ("Hawk" if (animal["can_fly"]) else "Penguin") if (animal["has_feathers"]) else ("Dolphin" if (animal["has_fins"]) else "Bear")
print(animal, animal_species)
Output:
{'has_feathers': True, 'can_fly': True, 'has_fins': False} Hawk
{'has_feathers': True, 'can_fly': False, 'has_fins': False} Penguin
{'has_feathers': False, 'can_fly': False, 'has_fins': True} Dolphin
{'has_feathers': False, 'can_fly': False, 'has_fins': False} Bear
Another Example of Ternary Operator in Python
Deciding whether to go and buy shampoo
In the next example of ternary operators, we want to be able to decide whether to buy shampoo or not. The ternary expression makes the decision based on the availability of shampoo and also based on if it is raining outside.
out_of_shampoo = True
raining = True
decision = ("Don't go to market" if raining else "Go to market") if out_of_shampoo else "Don't go to market"
print(decision)
We constructed the decision in such a way that if we are out of shampoo, and it is not raining outside, then we can go to the market. From the example, we are out of shampoo (out_of_shampoo = True
) and it is raining outside (raining = True
). So we will have the following output
Output:
Don't go to market
We can change the values of the variables such that we are out of shampoo (out_of_shampoo = True
), and it is not raining outside (raining = False
).
out_of_shampoo = True
raining = False
decision = ("Don't go to market" if raining else "Go to market") if out_of_shampoo else "Don't go to market"
print(decision)
The above code produces the following output
Output:
Finally, if we are not out of shampoo, and it is not raining outside, we will get the following changes to our code
Go to market
out_of_shampoo = False
raining = False
decision = ("Don't go to market" if raining else "Go to market") if out_of_shampoo else "Don't go to market"
print(decision)
When executed, we get the following output
Output:
Don't go to market
Conclusion
That’s it for this tutorial on python’s ternary operator. With this operator, you can write conditional statements as expressions that return a value based on a condition. Thank you for reading this post!
If you need help with python homework or looking for someone who can help with python then feel free to drop us a message.