Join Barron Stone for an in-depth discussion in this video If/else-if chains, part of Programming Fundamentals in the Real World.
- View Offline
- Every programming language has some form of the classical if-then-else statement. Each language may use different words and syntax for it but they all accomplish the same thing, which is to allow for conditional execution. The program is able to choose which code it executes based on some condition, such as the valuable variable, whether or not a file is empty, or any number of things. One of the first things that every new programmer learns is how to use an if-else statement, which allows your program to take one of two possible paths. If some condition do this, otherwise do that.
Things can get a bit more confusing when we start building complex conditional statements that have more than just two possible choices. The way we as humans make decisions among several different options is different than a computer. Computers can only make binary decisions which means it can only decide between two things at a time. So even complex conditional statements with lots of options really boil down to a sequence of binary choices for a computer to make. I've got some friends coming over later to eat pizza and play board games, which means I need to decide what type of pizza to order.
I want to be a good host by getting a pizza that all of my friends can enjoy so I should take into account any dietary restrictions that they have, when I make that decision. Fortunately, Olivia is here to help me figure that out. I've spent a bit too much time programming, so I tend to think like a computer. Olivia on the other hand is much more human. - Well, what kind of pizza should we get? - That is an open-ended question that I'm not prepared to handle as a computer. - Hmm. Well, is there anyone that can't eat meat? In which case we should get cheese pizza.
- Yes, Verne doesn't eat meet, therefore, we'll get a cheese pizza. - Wait, but hold on a second. - Decision made. - Verne's vegan, which means he can't have meat or cheese. We should get a vegan pizza instead. - Too late, the decision is made, no more questions. - Verne won't be able to eat it. - I'm not listening to you. - In addition to acting annoying, Verne's also acting like an if-else-if chain in a program. An if-else-if chain is a series of questions that are asked in order. The first question and only the first question whose answer is "yes" gets its corresponding actions performed.
Any questions after that are never considered. People tend to ask a series of questions that starts with very general, and then come more specific to narrow it down towards the final answer. An if-else-if chain also asks a series of questions but will choose the first true option even if the other conditions are also true. That means the if-else-if chain has a hierarchy. The cases that come firtst have a high priority than any other cases that follow it because they are evaluated first. - I'll stop acting like an annoying computer for now to show you some example code.
This Python's script called start_09_01_choose_pizza contains an if-elif-else statement which reproduces the conversation that I just had with Olivia to decide which pizza to order. Even though there are three possible outcomes from this structure: I can get the cheese pizza, the vegan pizza or something else - it arrives at a decision to a series of binary choices. Each of the expressions following an if and elif can be evaluated to a boolean value meaning that each expression is either true or false.
There are only two options. Your program will evaluate these expressions in order from top to bottom until it finds the one that's true. It'll execute the corresponding code and then leave the if-elif-else structure without looking at any items after it. There can be multiple expressions in the if-elif-else structure, but only the first one that evaluates to true will get chosen and executed. For this example, I've created a set called diet_restrictions, which are things Verne doesn't eat since he is a vegan.
I use this set in my if-elif-else statement to determine which pizza I should order. The first question that Olivia asked me was if there was anybody coming over who could not eat meat. This corresponds to the first expression in my structure, which will evaluate to true if meat is in the set of diet restrictions, which it is. The next expression on the elif-line will also evaluate to true because it checks to see if both meat and cheese are in Verne's diet restrictions, which they are.
When I run the script it says to order the cheese pizza, which is going to be a problem since Verne does not eat cheese. Because the first option - meat - evaluated to true it's selected that option and didn't even consider ordering a vegan pizza. This is the same problem that Olivia and I ran into during our conversation. She started by asking me the less restrictive question about if somebody does not eat meat. Since that was true I decided to execute that case and order the cheese pizza before she could ask me the more restrictive question involving meat and cheese.
It's very important to keep this hierarchy in mind when writing if-elif-else chains. The more restrictive options should go near the top of the statement where they have a higher priority. To fix this issue, first I'll modify the if-statement at the top to be the most restrictive option: meat and cheese. And if that evaluates to true then we'll order a vegan pizza. Next, I'll change the expression for the elif-statement to be the lest restrictive one by removing the requirement of cheese.
And if that evaluates to true then I'll order the cheese pizza. When I save and run this script again it selects the vegan pizza, which is the right choice given Verne's dietary restrictions. When you're writing an if-elif-else structure take the time to think about how the different cases relate to each other and decide which options should have the highest priority and come first in the sequence. You want to avoid the situation where an important, high priority condition never gets evaluated because it's too far down the if-elif-else chain and there are earlier conditions that also evaluate to true.
- Reusing functions
- Local vs. global variables
- Creating and naming custom objects
- Class inheritance
- Modules and packages
- Multidimensional lists and tuples
- Queues and stacks
- Creating and combining sets
- Storing data in dictionaries
- If/else and switch statements
- For vs. while loops
- Error handling
- Polling and event-driven programming