Intro to if-elif-else
This course is part of a series of content designed to help you learn to program with the Python programming language. We look at conditionals like if-elif-else and booleans.
- Describe the syntax of the if-family of conditionals.
- Describe the concept of a boolean.
- Explain the True and False keywords.
- Describe nesting conditionals.
This course was designed for first-time developers wanting to learn Python. Existing developers may want to skip.
This is an introductory course and doesn’t require any prior programming knowledge.
Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language.
Should you want to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: firstname.lastname@example.org. And one of our cloud experts will reply.
Certain pieces of code are kind of like a template. Take a look at this. This is the structure of an if statement with the optional else-if and else.
When Python reads an if statement it expects whatever is between the word if and the colon to be considered True. What does that mean? To be considered True?
We’re going to branch out and talk about booleans for a moment. This component of the language syntax is specifically designed for working with boolean objects. So before we cover if in-depth, we should go more in depth on booleans. Decision making in code revolves around the idea of something being in one of two possible states.
A thing can be:
on or off
true or false
0 or 1
The exact name of the two states isn’t really important in this case. What’s important is the idea of something being in one of two states. This concept of having two states - where only one can be active is modeled using Python’s bool object. The bool object can exist in one of two states. It can be True or False. Because these concepts are so common, the language includes keywords to represent them.
When the interpreter encounters the keyword True, it knows that you’re referencing a boolean object with the value of True. It’s the same for the False keyword. When the interpreter encounters False, it knows to reference a boolean with the value of False. We can use these keywords if we want to specifically bind a name to a True or False object. For example, we could bind the name “is_allergic_to_animals” to either True or False.
And while it’s possible to bind a name to the objects these keywords represent, it’s perhaps not as common as other means of producing booleans. Booleans are commonly produced as the result of performing operations or from calling code. For example the comparison operators return a boolean value after performing the comparison. We can even use the and, and or operators to compare two different boolean expressions. Which is another way to produce a boolean value.
For example: if either one of these comparisons are True, the results will be True. Everything between the if keyword and the colon has to evaluate to True. You can combine operators and objects within the confines of the syntax and as long as the results are True - the code under the if statement is going to run. This is the syntax for an if statement. The lowercase word if: followed by some condition that evaluates to True. And then a colon and a new line. A new line is what happens when you hit the enter or return key on the keyboard in a text editor.
Recall that Python uses whitespace based indentation to denote different blocks of code. And that the standard indentation is represented with four spaces at the start of each line underneath my if statement. Each line is indented with 4 spaces before the code for this section starts. In this example the if statement is coded to always be True. Which means this code block will be read by the interpreter. This block doesn’t actually do anything. It simply specifies the keyword pass. The pass keyword instructs the interpreter to do nothing. This has some limited use cases, such as showing valid demo code that does nothing. Or creating placeholders for future code while developing.
The else-if statement follows the same pattern as if. Whatever is between elif and the collon at the end must evaluate to true for this block to run. It starts with the lowercase text elif: followed by something that evaluates to True. That’s followed by a colon and a new line. The code that’s scoped to this elif statement is indented with the standard indentation. In this case we instruct the interpreter to pass again. The else statement is intended to be used for defaults that should be set if the other conditions aren’t True. It doesn’t perform any comparison. It’s simply the lowercase word else followed by a colon, a new line, the standard indentation and then the code for this block.
This is the syntax for conditional statements using if, else-if and else. Here’s a more complete example. Imagine we have two pieces of input. One is a person’s age and it’s bound to the name age with a value of 42. The other piece of data is a command to perform. Which is a string object bound to the name command. Let’s imagine the command is entered when the code is first run. If the command is in the list of these values here then we display this string. If the command isn’t in this first list we move on to the next statement which is the elif.
This line compares the command against this string and it compares the age binding to determine if the age is greater than 40. If both of these conditions are True then this code runs. If either is False the next line of code runs which compares the command to this string. If they match then this line of code is run. If none of these conditions are met, then the else block is run. This structure is like a building block that can be used in certain contexts. And those contexts will start to fall into place as you begin to read more Python code. For now, just know that this is a key build block for Python code. In fact, we can nest if statements. Allowing us to make a series of conditional decisions.
Recall that conditional statements are used to control the flow of code by making decisions. When we make decisions in real life, sometimes decisions depend on the results of previous decisions. For example: should we go out to dinner? If so, how about Himalayan? Because I know a great place.
In code we can create nested decisions. As a contrived example: Imagine we have some object bound to the name content. The object has an attribute named type which specifies the content type. And it has a method named isa_video which returns True or False. We could check if the content is a video. If so, then we move to the next if statement. Which is indented using the standard indentation. If the content type is equal to mpeg then we perform one action, otherwise another.
Nesting is common. However, as you progress with your coding skills you’ll get a sense for how many levels of nesting is common for your use cases. And how many is just confusing and should be restructured. Okay, this seems like a natural stopping point.
Here are your key takeaways:
The if-family of statements begin with the keyword followed by a condition which must evaluate to True for the code block to run.
A boolean object models the concept of something being in one of two possible states.
In particular Python uses the keyword True and False to represent the two states.
If statements can be nested which enables them to make more complex decisions.
Alright, hopefully this gets you started with the if-family of keywords. Thanks so much for watching. And I’ll see you in another lesson!
Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.