Today we’ll be talking about the if-elif-else statements used for decision making in Python.
Here’s the video version of the article:
We use the if statement to make conditions. There’s a colon after the condition and then comes the indented block of code.
Here’s an example:
Let’s create a variable called a and assign the value 10 to it:
>>> a = 10
Now let’s write some code which will only be executed on condition that our variable’s value is greater than 10, which it isn’t:
>>> if a > 10:
... print("It's a huge number.") # This will not be executed because a is not greater than 10
The three dots instead of the standard command prompt is Python’s way of saying that it’s waiting for the next line of a multiline statement.
To finish the block we need to enter an empty line in interactive mode. The block is only executed if the condition is true.
Let’s change the condition:
>>> if a ** 2 < a * 12:
... print("That's right.") # This code will be executed because 10 ** 2 < 10 * 12, so 100 < 120
...
That's right.
The else Block
We can add an else block. It’s executed if the condition is not met:
>>> if 4 > 5:
... print("It's strange!") # won’t be executed ‘cos it’s false
... else:
... print("That's it!") # so this code will be executed instead
...
That’s it!
The elif Blocks
We can add more conditions with elif:
pet = input("What pet do you have? ")
if pet == "dog":
print("You need some meat.")
elif pet == "cat":
print("You need some milk.")
elif pet == "hamster":
print("You need some carrots.")
else:
print("Never heard of such an animal.")
Here’s what we’ll get when we run the program and enter hamster as our input:
What pet do you have? hamster
You need some carrots.
There may be only one else statement, but there may be any number of elif statements. As soon as an elif condition is met, its conditional block is executed and the following elif statements are ignored. Here’s an example:
if 2 > 5:
print("2 > 5")
elif 2 < 5:
print("2 < 5")
elif 3 > 2:
print("3 > 2")
The condition in the if statement is false, so the work flow moves to the first elif statement and because the condition here is true, the code in the conditional block is executed. Although the condition in the second elif statement is also true, the code is not executed. Here’s the output:
2 < 5
Comparison Operators
You can use any comparison operator in the condition. We use a double equal sign for equality, because we use a single equal sign for assignment. Here are all the comparison operators that you can use:
Here’s an example with !=
>>> name1 = "Jenny"
>>> name2 = "Betty"
>>> if name1 != name2:
... print("These are two different names.")
... else:
... print("It's the same name.")
...
These are two different names.
Here’s an example with numbers:
>>> a = 500
>>> b = 150 * 3 + 55
>>>
>>> if a >= b:
... print("a >= b")
... else:
... print("a < b")
...
a < b