Kodeclik Blog
Python’s Inline If
Consider the following program to capture the state of a kid during a weekend:
playTennis = False
playSoccer = True
if playTennis:
happy = True
elif playSoccer:
happy = True
else:
happy = False
print(happy)
The output of the program is:
True
This program can be written in more compact form as follows:
playTennis = False
playSoccer = True
if playTennis or playSoccer:
happy = True
else:
happy = False
print(happy)
which will give the same output as before.
The “inline if” is an even more compact way to render the above program logic. We can rewrite the above program as:
playTennis = False
playSoccer = True
happy = True if (playTennis or playSoccer) else False
print(happy)
Note how the line “happy =” first lists the clause (output) if the condition is true, followed by the conditional, and then the clause if the condition is false using an else part. Thus, the “inline if” is just syntactic shorthand for the more usual way of writing if…else statements. It doesn’t add any new functionality but leads to more natural and readable code.
Difference between inline if and if...else
There is one key difference between the usual way of writing if…else statements and the inline if. An inline if definitely needs an “else” part whereas an if statement can get away without having an “else” part.
For instance, if we try:
playTennis = False
playSoccer = True
happy = True if (playTennis or playSoccer)
print(happy)
We will get the following error:
File "main.py", line 4
happy = True if (playTennis or playSoccer)
^
SyntaxError: invalid syntax
On the other hand, if we tried:
playTennis = False
playSoccer = True
if playTennis or playSoccer:
happy = True
This program works and leads to the output:
True
Of course, if the variables playTennis and playSoccer were both defined to be false, you will get an error when you try to print(happy) because happy would not have been defined (due to the absence of an else clause).
If you do not really have anything to do in the “else” part, you can write your program as follows using an “else None” clause.
playTennis = False
playSoccer = True
happy = True if (playTennis or playSoccer) else None
print(happy)
The output will be:
True
If we set both variables to False, we get:
playTennis = False
playSoccer = False
happy = True if (playTennis or playSoccer) else None
print(happy)
The output is:
None
Note that None is used to define a “null” value, or an undefined. (It is not the same as False.) None is an accepted value for variables in Python which is why the print statement following the “inline if” does not complain.
Python’s inline if is also known as a ternary operator and is covered in our blogpost on ternary operators.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.