Building on the if else
foundation from the previous lesson,
we will explore two efficient alternatives: the one-line if else
statement and the match case
block.
if else
StatementWhen we created an if else
block in the previous lesson,
it spanned several lines due to the requirement of incorporating colons
after each conditional expression. However, if the actions
within these expressions are quite straightforward, we can opt for a
more condensed representation using the one-line if else
statement.
Let's break down the structure of this statement. The format is:
a if (condition) else b
. This encompasses three
components: the condition parameter, which was immediately
after the if
previously, is no moved to the middle of the
statement. The a parameter, which contains the return value if the
condition yields True; and the b parameter, which returns
the value if False resides. To illustrate
this concept further, we'll demonstrate how to condense the
if else
block from the 3rd code editor in the previous lesson
into a streamlined one-line if else
statement.
One difference here is that the ifelse
function will
return the value of the expression that is executed, whereas the
if else
block will not return anything. This means that
we can assign the result of the ifelse
function to a
variable, as we did with y
in the example above, so
that we may print it out.
In the previous lesson, we explored the use of
if, elif, else
conditions to examine multiple scenarios.
While it is entirely possible to add more elif
statements
to encompass additional conditions, doing so can lead to extensive,
hard-to-maintain code. A more efficient and tidy approach is to utilize
the match case
block, which enables us to inspect a
series of conditions and allot a value corresponding to the true
condition. Feel free to change the value of a to see the
different outputs.
Now let's see the same code but this time using
multiple if, else if, else
conditions.
This will have the same result, however as we can see
the code is much more verbose.