Testing multiple conditions
In this lesson, we will build on our understanding of the if statement by introducing the elif and else statements to handle multiple conditions and create more complex decision-making logic in Python.
Let's go back to our temperature example. We already know that the program will log that it's warm outside if the temperature is above 70.
temperature = 75
if temperature > 70:
print("It's warm outside")
But what if we also want to inform the user if it's cold outside, say if the temperature is below or equal to 70?
We could add another if
-statement.
temperature = 60
if temperature > 70:
print("It's warm outside")
if temperature <= 70:
print("It's cold outside")
That works, but it feels a bit tedious. We have to write another condition for the exact opposite of the first one.
Fortunately, there is a better way to write this in Python: the else
-statement.
Let's give it a try:
temperature = 60
if temperature > 70:
print("It's warm outside")
else:
print("It's cold outside")
The code does exactly the same as before, but without the need to write another condition. Instead, we are using an else
-statement.
The else
-statement provides a fallback option to execute a block of code when the preceding condition of the if
-statement evaluates to false.
Let's check if it also works for warm weather:
temperature = 75
if temperature > 70:
print("It's warm outside")
else:
print("It's cold outside")
Since the condition of the if
-statement is met, the else
block is ignored.
Great! But what if you need to include another condition? Some people might argue that temperatures below 71 degrees are not considered cold.
Suppose that temperatures between 51 and 70 degrees are neither cold nor warm. We can use a so called elif
-statement for this scenario.
Let's give it a try:
temperature = 60
if temperature > 70:
print("It's warm outside")
elif temperature > 50:
print("It's neither cold nor warm outside")
else:
print("It's cold outside")
Great! In this scenario, the first condition that is fulfilled triggers its respective code block, and all other code blocks are not executed.
elif
, short for 'else if', checks another condition if the previous ones are false.
You can have multiple elif
-statements.
temperature = 45
if temperature > 70:
print("It's warm outside")
elif temperature > 50:
print("It's neither cold nor warm outside")
elif temperature > 40:
print("It's a bit chilly outside")
else:
print("It's cold outside")
Let's check if you understood.
What will be the output?
num = 5
if num > 10:
num = num + 5
else:
num = 0
print(num)
What will be the output?
num = 50
if num > 10:
num = 15
if num > 5:
num = 0
print(num)
What will be the output?
num = 50
if num > 10:
num = 15
elif num > 5:
num = 0
print(num)