Some might say that Booleans make your life more simple. With them, it's either this or that, either True or False.
But you can also make the world more complicated than that. And Python is happy to help you tackle that decision complexity as well by using another keyword for conditional statements called elif, which stands for else if.
elif Python Example
If you are confronted with a slightly more nuanced decision than Hamlet, you need more than just two options.
At least the decision you'll need to take is much less impactful than his: After opening your fridge, you find that you have an apple and a pizza at home. Now, what should you eat? Time to consult with your inner hunger levels and run that by your conditional decision-maker:
hunger = "small"
if hunger == "big":
print("Eat the pizza")
elif hunger == "small":
print("Eat the apple")
else:
print("Don't eat anything")
Functionality of Python Elif
Both expressions following the if and the elif keywords consult the value of the hunger variable and compare it to a hard-coded string:
ifchecks whether the value ofhungeris equal to"big"elifchecks whether the value ofhungeris equal to"small"
Only one of the code blocks associated with these checks will ever execute. If the hunger variable points to the string "big", then your code would print "Eat the pizza". The rest of your conditional construct would get skipped, meaning that neither the elif nor the else check would ever even run.
Break Down the Example
In your case, however, the hunger variable points to the string "small". So this is what happens here:
- The
ifstatement checks whether thehungervariable points to the string"big" - Since it doesn't, the indented code block under
ifgets skipped - The
elifstatement checks whether thehungervariable points to the string"small" - Since it does, the indented code block under
elifgets executed - The string
"Eat the apple"gets printed to your console - Since the expression following the
elifkeyword evaluated toTrueand the associated code block ran, Python skips the following two lines associated with theelsekeyword
If the hunger variable had pointed to anything else aside from "big" or "small", then the else keyword would have sprung into action. The indented code block that follows it would have executed, and your code would have printed the string "Don't eat anything".
Info: The else keyword is a catch-all. Your hunger variable can have any other value, even if it is of a different type, such as a number. The else keyword will execute unless one of the if or elif keywords above has. If you don't want that, then you don't need to use an else block.
Great! Thanks to your thorough hunger introspection and your trusted decision-maker code, you ate just what you wanted to eat. However, what about if your hunger level would have been... "medium"?
In your case, the code would have told you not to eat anything, but that wouldn't have satisfied your belly!
Multiple Elif Statements
Python allows you to chain as many elif keywords into your decision-making code as you want to. There are no limits to this! You can make your world of decisions as complicated as you want to.
Continue Previous Example
Add another elif statement that covers your cravings when your hunger level is "medium". Add a third elif statement that helps you to handle a "giant" craving.
Up to now, you have only compared strings to other strings using the equality operator (==). As you learned earlier, there are a lot of other Python operators to choose from when making decisions.
Some of them introduce a little trickery that you need to be aware of when working with conditional statements, namely that there is a specific order of execution of these statements that goes from top to bottom.
Conditional Order Of Execution
Conditional statements get executed from top to bottom, line-by-line. If the first if statement catches, then the other conditionals get skipped completely. If the next elif statement catches, then the remaining parts of your conditional statement won't execute. And so it continues.
Info: A line in a conditional statement only gets executed if the line above it didn't catch.
This is why you need to consider how you structure your checks and where you place them in the overall conditional block.
Prevent Errors
Consider the code block below, where you want to find out whether a number is divisible by two or four. At first glance, the code looks fine:
number = 2
if number % 2 == 0:
print("divisible by two")
elif number % 4 == 0:
print("divisible by four")
else:
print("not divisible by two or four")
Go ahead and run the code. See how it returns the expected solution when you pass in values such as 2, 5, or 10.
However, there's a problem with this code snippet that relates to the sequential order of execution of statements in a conditional code block. Can you spot it? What happens when you enter the value 4 as the number?
As you might have discovered, the first conditional statement if number % 2 == 0 will catch when you run the code using 4 as the value of number. The reason for this is that 4 is divisible by 2 without a remainder. Therefore, the first expression following the if keyword returns True, and the rest of your conditional code block gets skipped.
However, you wanted to print a different message if the number was divisible by 4! Remembering that the code gets executed line-by-line and that subsequent lines get skipped if one statement catches, you can refactor the code to work as expected:
number = 4
if number % 4 == 0:
print("divisible by four")
elif number % 2 == 0:
print("divisible by two")
else:
print("not divisible by two or four")
By changing the order of the checks you apply to your number, you first catch all the values that are divisible by four. Only values that aren't will be passed forward to the elif check. Those that are divisible by 2 but not by 4 will catch here, and the rest gets passed on to your else statement.
After learning about conditional statements, you will get to know another way you can control the flow of execution in your programs through Python loops. Read more about them starting in an upcoming lesson.
Additional Resources
- Control Flow: The if Statement
Summary: Python Elif Statement
elifadds another conditional layer to theif elsestatement block- Multiple
elifstatements can be added inside of the conditional block - The order of execution in conditional statements is from top to bottom
- Errors can occur when the desired condition for a desired value is not met since a previous condition catches it
Functionality of Elif
- Required:
ifstatements can exist by themselves, butelifandelsestatements require anifstatement before them. - Unlimited: You can use as many
elifstatements as you want to. - Optional:
elseand multipleelifstatements are optional. - Ordered: Conditional statements execute from top to bottom. Order matters.
- Skipped: If one statement catches, then the subsequent ones get skipped.
Remember, if your conditional logic doesn't produce the output you expected, check the order in which you wrote your conditional checks.