Ternary operator
Something that I came across today that I don’t use often are ternary operators in Python. These are just conditional statements that are written succintly in a line:
1
[on_true] if [expression] else [on_false]
Using the following code as an example:
1
2
3
4
5
6
7
8
9
10
weather = input("What's the weather? ")
if weather == "sunny":
activity = "have a picnic"
elif weather == "rainy":
activity = "watch a movie"
else:
activity = "do anything"
print(f"Let's {activity} since the weather is {weather}.")
Running the code will look something like this:
1
2
3
4
5
6
7
8
What's the weather? sunny
Let's have a picnic since the weather is sunny.
What's the weather? rainy
Let's watch a movie since the weather is rainy.
What's the weather? blah
Let's do anything since the weather is blah.
The if-else statement above can be written in a line so the code can also be:
1
2
3
4
5
6
7
weather = input("What's the weather? ")
activity = "have a picnic" if weather == "sunny" else \
"watch a movie" if weather == "rainy" else \
"do anything"
print(f"Let's {activity} since the weather is {weather}.")
The use-case can be read like an English sentence:
“Let’s have a picnic if the weather is sunny. Else, let’s watch a movie if the weather is rainy. If it’s neither of those, let’s do anything!”
There are many interesting ways by which ternary operators can be written - using tuples, dictionaries and lambdas (although when to use lambdas for this is beyond me rn). The conditionals are in square brackets [ ]
, 0
evaluates to False
and any other number to True
.