The if-elif-else Statement
Learn about the functionality and key properties of the if-elif-else statement in Python for handling multiple conditions.
The if-else
statement handles two sides of the same condition: True
and False
. This works very well if we’re working with a problem that only has two outcomes. However, in programming, it isn’t always a True
or False
scenario, and a problem can have multiple outcomes. For instance, a grading program may have only pass or fail outcomes, but more often there are multiple different grades that are possible. This is where the if-elif-else
statement shines. It is the most comprehensive conditional statement because it allows us to create multiple conditions easily. The elif
stands for else if, indicating that if the previous condition fails, try this one.
Structure
The if
and else
blocks will remain the same. The elif
statement comes in between the two.
Let’s write an if-elif-else
statement which checks the state of a traffic signal and generates the appropriate response. Our AI Mentor can explain the code as well.
light = "Red"if light == "Green":print("Go")elif light == "Yellow":print("Caution")elif light == "Red":print("Stop")else:print("Incorrect light signal")
Now, our conditional statement caters to all possible values of light
.
Try changing the value and see how the response changes.
Multiple elif
Statements
This is the beauty of the if-elif-else
statement. We can have as many elif
statements as we require, as long as they come between if
and else
.
Note: An
if-elif
statement can exist on its own without anelse
block at the end. However, anelif
cannot exist without anif
statement preceding it (which naturally makes sense).
Let’s write a piece of code that checks whether the value of an integer is in the range of 0-9
and prints the word in English:
num = 5if num == 0:print("Zero")elif num == 1:print("One")elif num == 2:print("Two")elif num == 3:print("Three")elif num == 4:print("Four")elif num == 5:print("Five")elif num == 6:print("Six")elif num == 7:print("Seven")elif num == 8:print("Eight")elif num == 9:print("Nine")