We now know how to use data and variables to make a statement so lets learn how to execute code based on the result of that statement. In this video, we will learn 3 tools, the if, else and elif keywords. These functions can be used to execute (or not execute code) depending on the statements that we give it, and control the flow of our code.

Transcript

We just learned how to evaluate and analyze information by making a statement with operators, and now we're going to learn how to use the if-else structure to make decisions and execute code depending on the result of those statements. We've already touched on this structure before, but in this video we're going to formally go over it and in a bit more depth with some examples.

There are only three things we need to learn here, if-else and else-if, which is a combination of the two. So we're just going to go along and write a really simple program that takes in a score and then gives it like a grade rating based on what percentage that score is. We're going to start by just creating a score here, and this is what we can change to run through the different logic we're going to create, and then we're going to create a grade here, and we're going to start it by being not marked, just in case we don't update it we can see, oh, our logic didn't update.

And now here, we're going to start with our if statement, and it's really easy, it is the if keyword followed by a condition, so we're going to say if score is greater than or equal to 50, and we're just going to put a column there, and then whatever we indent into it is what will be run if that condition is true. So we're just going to say in this circumstance, grade is equal to pass, and we're just going to assign a string to that. And then we're just going to add a print at the end, and we're just going to print, grade, sweet. And if we run this, we can see that our score of 70 goes through that if check, it is above 50, so it passes. Now if we do less than 50, nothing happens, because we haven't told it, we haven't created logic to say anything below 50 is a fail.

And this is where we can use an else statement, we can say else grade equals fail. So if the if statement above it is not true, then the else is going to execute the code in it, really straightforward. And if we run that, we get a fail, sweet. That's what we need, that's a success in our books. There is another way we could have done that though, we could have instead said, if score is less than 50, then it's a fail. And that's going to return the exact same result. And you can actually just keep chaining if checks over and over and over if your program needs it. I'm just going to go back to else here, because it's a nice little catch for anything that we might miss in our if logic.

Now let's say we want to upgrade this to just going from a pass to a fail, to maybe assigning a letter to it, like A, B, C, D, or F. So what I'm going to do here is, I'm now going to say if the score is above or equal to 90, it's going to be an A, and then I'm just going to chain some of them together. So above 75 is going to, oh sorry, let's do 75 for an A, and 65 for a B, and 54 a C, and then a 40 or greater for a D, sweet. And then anything else is going to be an F, and above 40 is a D, sweet. We've got our score set to 90, and if we run it, we get a D. What's going on there? If we set this to 60, we still get a D, but if we set it to 30, we get an F.

So there's something going on here with our D here, because if it's below 40, it's going to be correct and be an F, but anything above 40 is going to be reported as a D. And this is because of how the if works. Each of these ifs here is its own independent check. So let's say that score is equal to 90. We make this check, score is above 75, so it's equal to A, but it's also above 65, because this again checks independently, so it's a B, and then it's also above 50, so then it updates it to C, and it also is above 40, so it updates it to a D, and that is the last check that we make with that. So the final result is that it's D.

This is where our friend else-if comes along. If we just simply write else-if here it will magically fix everything.

So what's going on here? Well, an else-if is just an else and an if kind of put together, and so all of these checks are no longer completely independent. You can kind of think of an elif as if any of the checks above were true, then you can ignore this.

So let's say it's 70 and we run it, we're going to get a B. So first of all, we make our first if check. Is it above 75? No. Okay, next one. And then we go else-if. Is it above 65? Yes, it is. So it's a B. And this elif here means that it skips all the other else's in there, and we just finished there.

We're dealing with some really tricky logic here, so I'm actually going to expand out the else-if because it will help kind of demonstrate what's going on here. Okay, so we've expanded this out a little bit, and now I've got else-if and else-if and else-if, and elif is just else and an if put together. This is exactly the same code as before, it's just spread out more. And this might make it a little bit more clear.

So the score is 70. Is it above 75? No. Okay, so the else here is going to run the code that's inside of it, and inside of that is another if. So if the score is above 65, it is, so the grade is B. And so this else is not going to run because this if was true, which means that all the other checks in here won't run. And this stops that issue we were having when we had only if statements.

And I'm just going to condense it back down to elifs, which, by the way, is exactly the same code, it's just a lot neater way to write it all. So there you go. If statements act independently on each check, and elif statements are kind of dependent on the checks before it. This difference between if and elif is a little bit tricky, and when you start getting ifs inside ifs inside elifs, it can really get confusing. So it's always a good idea that when you use logic, just really, really triple check that you've got your logic down pat.

All right, let's get practical and build an example. I've currently got open the demo code, which can be found on our course page on our website. Link in the description for our YouTube audience. The if else structure isn't terribly hard. So in this demo code, we're going to introduce some unique applications of it in this volume control simulation. If we run the code, you can see that as we turn the potentiometer, we control the volume here in the shell, exactly like you would on a TV. And instead of printing it continuously, you can see that it only prints it when we change the value of the potentiometer.

So we start by setting up a potentiometer plugged into pin 26. So wire that up if you haven't done so already. And then we have this constant here that we're going to use to map the ADC to go from zero to a hundred very nicely. Now here we're creating a string, which you can either put an A or a B inside of. We have our main while true loop here, and we've also got another one down here. This one's inside if method equals A, and this one's inside if method equals B. And this allows us to choose which bit of code we want to run here based on what we set this string as.

So you can choose it to run either method A or method B, and this is a really handy tool to have when you're developing code, but this could be applied in other ways. For example, you could have a switch, and when you turn on the Pico and it's switched this way, it will start up in mode A, and if you switch it the other way and turn on, it will start up in mode B.

So then in our while true loop, we start by reading the potentiometer, and then we have another if statement here. This compares the current volume reading coming from our potentiometer to the last one, and if the difference is greater than two, or it is less than...Negative two, it executes the code inside of it. And this little if statement here stops the code from printing continuously. It's the part that makes it only print when we change the volume.

Then we have a very long if else structure nested inside of that, and this checks if the volume is between zero and 10, or 10 and 20, or 20 and 30, and if it is, then it will print out the appropriate volume bar text. And because we're using elif here, once one of these returns true, it won't even check the rest of them. It's just going to skip over them.

And then at the bottom, we update our last volume and put it to sleep for a little bit. Now this is a very inefficient way of doing that, and there is a better way to do so, which is method B.

So we would go up to here, change this to use method B, and run. And you should see, if we just make that a little bit bigger, that it behaves exactly the same. And that's because the code is identical to method A, except for the part of that really long if else chain. It instead uses these two lines here to calculate the bar to print, to figure out what it needs to print. Much more efficient way of doing it if you want to check it out.

All right, three key takeaways. One, the if else statement executes code if the statement we attach to it is true. Two, we can follow it with an else statement, which will execute the code inside of it when the if statement immediately above it is false. And three, the elif statement is an else and an if statement put together.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.