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.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.