-
Book Overview & Buying
-
Table Of Contents
Python Illustrated
By :
The ternary operator allows you to write basic if...else statements in one line. It might be a bit difficult to read at first. Here’s what the syntax looks like:
value_if_true if condition else value_if_false
So, let’s say we decide what to do based on the time:
hour = 14 # 2 PM
activity = "Nap time" if hour < 17 else "Play time"
print(activity)
Can you guess what this outputs? It prints the following:
Nap time
Don’t worry if you find it difficult. Let me explain. Since hour < 17 is True, activity is set to "Nap time" because that’s the first value. It reads like this:
It is "Nap time" if the hour variable is smaller than 17, else it is "Play time".

Again, you don’t need to write the code like this yourself. At some point in time, you might be more ready for it and write code like this. You’ll have to be able to read it, though...