Conditionals
Conditionals allow you to execute instructions only if a certain condition is true.
if
Its simplest form is:
where the condition can be for example a comparison between two values.
Indentation
The block of instructions is moved to the right by 4 spaces, or one tab. That's what we call indentation and we use it to identify the instructions that need to be executed if the condition is true.
elif
Sometimes you want to test if a condition is true and if not, you want to test another condition. And if the other condition is not true either, you may want to test another condition, etc. In order to achieve this, you can add as many elif
as you want:
if condition:
instructions
elif condition:
instructions
elif condition:
instructions
...
else
And finally, if you want to select all the cases where no conditions written before are true, you can use the keyword else
. You can only add one else
at the very end of your conditional statement. It does not need any condition since it will use the opposite of the conditions written before.
if condition:
instructions
elif condition:
instructions
elif condition:
instructions
...
else:
instructions
Examples
This code will execute the instruction to print the message only if the value saved in the variable age respects the condition >=18
.
number = int(input("Give me a number: "))
if number < 0:
print("The number is negative.")
elif number > 5:
print("The number is higher than 5.")
elif number == 3:
print("The number is equal to 3.")
else:
print("The number is not negative, not higher than 5 and not equal to 3.")
This code will execute the right instructions based on the value saved in the variable number.
If the value is negative, it will say that is negative. Else if the value is higher than 5, it will say that the number is higher than 5. Else if the value is equal to 3, it will say that it is equal to 3. If none of those conditions are met, it will execute the instruction after the else
.
Indentation
As explained above, the indentation (moving your instruction 4 spaces to the right) is very important in Python. Let's compare those two script:
When you execute the first one, Goodbye
will be printed each time, no matter the value of x.
However, the second one will print Goodbye
only if x is higher than 0. The instruction print("Goodbye")
is indented, so it is part of the if and executed only if the condition is true.