Kodeclik Blog

Python’s Inline If

Consider the following program to capture the state of a kid during a weekend:
The output of the program is:
This program can be written in more compact form as follows:
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:
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:
We will get the following error:
On the other hand, if we tried:
This program works and leads to the output:
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.
The output will be:
If we set both variables to False, we get:
The output is:
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.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.