In Python, the conditional if else is used when we want to execute instructions only if a certain condition is true or if it is false. If a condition is false we can use the else.
To be clear if else is the instruction that, using the flow charts, we have represented with the rhombus and the two branches, that of the true and that of the false, as explained in this lesson: block diagrams.
If else sintax in Python
The syntax of the instruction is therefore this:
if condition:
instructions_if # indentation (4 empty spaces)
else:
instructions_else # indentation (4 empty spaces)
Where condition represents the test we want to submit and if this is true the instructions_if block is executed, otherwise the instructions_else block. The instruction can also be just one.
Note that after the if condition and after else there are a colon (:), they indicate the beginning of each block of instructions.
In addition, each instruction must necessarily have an indentation equal to 4 empty spaces.
Examples on the if else statement in Python
Taking a number a as input, we want to see if it’s a number greater than or equal to zero or negative.
So the condition to check is: a >= 0?
If the condition is true we display in output that the number is positive or null, otherwise we display that it is negative.
So our simple Python script using the if else statement will look like this:
'''
We check if a number taken as input is positive or negative.
Examples on the if ... else statement
'''
a = int(input('Insert a number: '))
if a >= 0:
print('positive or null number')
else:
print('negative number')
In the event that we don’t want to view the message inherent to the else, we can also omit it, as in the example below:
a = int(input('Insert a number: '))
if a >= 0:
print('positive or null number')
Conclusions
In this lesson we have seen only very simple examples on the use of if else in Python, in the next lesson we will see the use of multiple selection.