Lesson 3. Conditions: if, then, else
6/15. Sometimes you don't need else
You can omit the
else
keyword and the whole false-block if nothing should be
done if the condition is false. Consider the problem of calculating the absolute value of x
and look at the code section.Indeed, the variable
x
has to be assigned to -x
only if x < 0
. Otherwise, it has to remain the same and we don't need to handle this case, don't need to do something with it.The instruction
print(x)
is executed anyway, because it is not indented,
so it doesn't belong to the true-block.Indentation is the general way in Python to separate blocks of code. All instructions within the same block should be indented the same way, i.e. they should have the same number of spaces at the beginning of the line. It is recommended to use 4 spaces for indentation.
In most of other languages the curly braces
{
and }
are used to form blocks.
The creators of Python decided to replace {...}
-like blocks with indentation.
This is the question of habit, but, to our opinion, indentation makes your code far more readable than keeping an eye on all the curly braces. x = int(input()) if x < 0: x = -x print(x)