While loops are the other type of loop we can use and they utilise the boolean logic statements we constructed before. Whilst for loops are designed to loop a set and a known amount of times, while loops will keep continuously looping a section of code until the statement we give it returns false. In this video, we will go over how to use while loops with boolean logic, and also take a look at the break and continue functions, and some handy tools when dealing with loops.

Transcript

We just learned about for loops and now it's time to learn about while loops. When we use for loops, we loop them for a predetermined amount of times, but a while loop, on the other hand, loops over and over until a certain condition is met. This type of loop uses Boolean logic, and we'll have our while followed by a statement that we'll attach to it, and while that statement is true, the while loop will keep looping over and over.

This is how that while true loop in a lot of our code works. We manually put the Boolean true there so it keeps looping over and over forever. But usually when we use a while loop, we don't want it to loop forever, so we do something like this. We have the while keyword up here, followed by some statement, a colon, and then we indent into it the code that we want to keep looping while this condition here is true. Nice and straightforward.

Here I've set up the loop to check if X is not equal to 20. Then inside the while loop, I set X to a random number between 0 and 20, print it off, and sleep for a little bit. And as you can see, it's going to keep cycling through and generating numbers until it reaches 20, in which the statement up here becomes false, and the while loop stops.

This is a bit of a weird example here, but instead of setting X to a random number, we could be reading an analog input, maybe the temperature of something, and then in the statement we could be checking if the temperature is less than 100 and doing something, and then when it goes over 100, that loop stops and we do something after that.

Something to watch out for is that we have to declare X here, or at least before the while loop, before we check it, otherwise it's going to give us some errors. And usually once you're inside the loop, we're going to be updating the value of X, or we might get stuck inside of that loop forever. And just a quick little handy tip, this function here, random int, it's a standard MicroPython library from the random library up here, really great way to generate random numbers in your code.

So that is pretty much it for while loops, it's not too much to know, but I want to show you two functions that are mighty helpful when using loops, and they work in both while loops and for loops. Let's start with the break function. When you call this function inside of a loop, it will immediately stop that loop. Regardless of if the conditions are met or not, and it's going to move on to the next thing after that loop.

We've got a slightly different setup here. Now the code will run as long as our number is greater than 5, because it will keep returning true. And I'm setting that variable to a number between 0 and 1000. So the odds of this statement here being true is pretty darn good. And as you can see, we've also set up a button on pin 15 with a little if statement. So if the button is pressed, the break command will run. So if I run this code, we can expect that to keep going for a good amount of time. And if I press the button, that break statement is going to activate and the loop is going to stop dead in its tracks, even though that Boolean condition has not returned true.

The continue function is a similar idea. And when we call it, instead of stopping the loop entirely, it will skip whatever is left inside of the loop and start the next cycle of that loop. For example, this is the same code as last time, but I've removed the button and the break part of it and put in this continue here. And that continue is only going to run if the number that is generated is greater than 100. So let's say we get to here, the number generated is 200. It will come to the if statement, which will be true, and then it will execute the continue and then it's going to go up to the top again. And the print and the sleep are going to be skipped completely, So if we hit run, we can see that it's not printing any number larger than 100 because any number larger than 100 is going to activate that continue and it's not going to be printed. These break and continue statements aren't going to be used in every single loop you make. In fact, you might not very commonly use them at all, but they are very important to at least know about because when you need them, you will need them

Let's dive into an application of a while loop and build something cool. Let's make a reaction test game. You will need the demo code, which can be found on our course page on our website, link in the description for our YouTube audience. And you'll also need an LED connected to pin 16 and a button on pin 15.

If we run the code, you can see that the game is going to prompt you to press the button to start the game. In which it will say ready. And once that LED turns on, press the button as fast as you can. And then the game reports back with your reaction time.

Our code starts by importing relevant libraries and setting up our pins here. Then in our main while true loop, we start by saying press the button. Then we will reset our button state to zero here just before we have this while loop here. And that's going to be looping as long as the button isn't pressed.

And inside our while loop, the only thing we're doing is updating that button state. And what this means is that this while loop will wait for a button press because it will keep looping over and over. And when we press the button, it'll be set to one. And then that statement will become false and it will move on to the next thing.

Once we press the button, it's going to print ready. And then it's going to put the peeker to sleep for a random time between two to five seconds. And then turn the LED on.

We're about to stumble into something we haven't learned yet. And that is time.tickms. When you turn the peeker on, it starts counting how long it has been running for. And we can get that length of time with time.tickms. So we store what the current time is. And then we have another while button waiting thing. It's exactly like the first one.

And once we press this button and proceed past the while loop, it's going to get the current time again. And then the stored time. And then use them to calculate how long it's been since we pressed the button. Then the LED turns off and we print your reaction time to the shell.

Now this is a bit more of an involved example than what we're used to. So have a look at it. Play around with it if you want. But if you can, wrap your head around how we're using the while loops here. You're set. Also, don't stress too much about the time.tick function. It's just handy to remember in case you need to deal with anything time-related like we're doing so here. And it might be worth remembering how we're using the while loops here to wait for a button press. Because that is a simple yet powerful tool to know.

Alright. Three key takeaways. One. We have the while loop with a statement. And as long as that statement is true, the code that we indent into it will keep looping over and over. Two. The break function can be called inside of a while or a for loop to immediately exit and stop that loop from happening. Even if that condition has not been satisfied. And three. The continue function can also be called to immediately move on to the next cycle of the loop and skip anything that is remaining in the current loop cycle.

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.