yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

break and continue | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

We may sometimes want to alter the normal control flow of our loops to either terminate early or skip an iteration. To do this, we can use the break and continue statements. A break statement tells the computer to immediately terminate the loop. We write it with just the keyword break.

Normally, this loop repeats a hundred times, but if I add a break statement here, it only repeats once, or really even one half times. We execute this first print statement, then we hit the break, and that tells us to immediately exit the loop. So, we skip any remaining lines of code inside the loop body. Now, this code isn't particularly useful. Why have a loop if I'm just going to terminate it immediately?

Instead, we typically combine a break statement with a conditional, so we only execute the break if a certain condition becomes true. Now, the break statement only executes when the loop variable reaches 10, so the loop repeats a full 10 times before it hits this break statement and terminates. Better, but why have the loop repeat a hundred times in the first place if it's always going to exit on the 11th iteration?

Let's take a look at a real example where a break statement might actually be useful. Here, I have a very simple climate simulation that models global temperature change based on CO2 emissions. My team has determined that climate effects become critical when the global temperature reaches 15.8 degrees Celsius. But if we do hit that limit, our simulation has already failed. We don't really care about measuring the temperature on subsequent years at that point.

That means what we really want is to also terminate the loop. We don't want the computer to bother doing all this extra work on these calculations that we don't care about. So maybe I think about writing a compound loop condition that checks both the year and the temperature. But if the loop terminates because of the temperature case, I still want to print that warning.

There are many different ways I can try and maneuver this code so both things happen, where I terminate the loop if the temperature exceeds a limit and print the warning. However, the easiest way to accomplish both tasks is to use a break statement because I want something specific to happen under one of those termination conditions.

It's better to use a conditional with a break statement instead of a compound loop condition. Then any code I want to run before I terminate the loop, in that case, I can just put inside the conditional. The continue statement skips the rest of the current iteration of the loop, execution immediately jumps back to the top of the loop, and then the computer continues with the next iteration as normal.

Let's go back to our original example with a loop that repeats a hundred times. If I stick a continue statement in the middle, the computer skips the bottom half of the loop body on every iteration. It executes the first print statement, and then it hits the continue, so it jumps back to the top of the loop to start the next iteration. That means we skip the rest of the current iteration, so we don't execute this final print statement inside the loop body. Again, not super useful. If we never execute this final print statement, why bother having it in the first place?

Just like the break statement, we typically combine continue statements with a conditional. Now, we only execute the continue statement when the loop variable I equals 10. That means we're only skipping the bottom of the 11th iteration.

Now, let's take a look at a more realistic continue example. Here, we have a loop to simulate an online store. We want to keep accepting orders for jars of jam until we run out of inventory. But we want to add some input validation so we don't accidentally sell more jars than we have, in case we end up in a situation where we only have a few jars left and a huge bulk order comes in.

So maybe we add a conditional here that checks that the order size is greater than the number of remaining jars, and we only process the order if the order size is okay. If an order comes in for a hundred jars and we only have ten left, we don't want to shut down the store; we just want to tell that specific user we can't fulfill their order right now, but continue to accept other orders to try and sell those last ten jars.

Alright, my loop works, but now I'm several layers of nesting deep. I have an if nested inside an else nested inside a while, and with all this indentation going on, this code is kind of hard to read. This is where the continue statement comes to the rescue. Instead of having this whole if-else situation inside the loop body, I can just check the invalid condition and put a continue there.

Then all this order processing code that I want to run on a typical iteration doesn’t have to be double nested. If the order size is too big, we'll hit the continue statement and jump back to the top of the loop, which skips all the order processing code below it for that iteration.

Break and continue statements are powerful tools for modifying the control flow of our loops. Break statements allow us to skip unnecessary work by terminating a loop early in an error case or in cases where we want to react to a specific termination condition. Continue statements allow us to skip doing the work on iterations where we have invalid or non-meaningful data, and they allow us to avoid deep nesting by checking for those invalid cases up front.

However, we should be careful about overly relying on break and continue. They should never be substitutes for writing meaningful loop conditions in the first place.

More Articles

View All
Camo Sharks: Breaching Test | SharkFest | National Geographic
RYAN JOHNSON: One of the most important tests that we’re going to do is the breaching test. GIBBS KUGURU: Breaching is sort of this ambush attack. They need speed, power, stealth. RYAN JOHNSON: This is when we’re going to be able to measure the color of…
The aftermath... Tenants Stopped Paying Rent
What’s big, eyes? It’s Graham here. So last month, I addressed a highly publicized article which found that nearly 1⁄3 of Americans were unable to pay their rent for the month of April. At the time, that was a very alarming statistic. For someone who has…
Feeding the Cheetah Triplets | Magic of Disney's Animal Kingdom
I don’t go to the gym very often. It’s a real workout. Gotta come and shift the girls in. So every single day we’re doing this trek in the land of Africa. Five-year-old cheetah triplets Maathai, Murie, and Fossey wait for keeper Dominique to serve breakf…
Trig limit using pythagorean identity | Limits and continuity | AP Calculus AB | Khan Academy
Let’s see if we can find the limit as theta approaches 0 of ( \frac{1 - \cos(\theta)}{2 \sin^2(\theta)} ). And like always, pause the video and see if you could work through this. Alright, well our first temptation is to say, well, this is going to be th…
Estimating actual COVID 19 cases (novel corona virus infections) in an area based on deaths
The goal of this video is to help us all estimate the actual new COVID-19 cases per day in your area, and it’s based on analysis by Thomas Pueyo. He wrote an incredible blog post on Medium; this is the link, and I’ll also include it in the description bel…
Capturing the Iditarod - Behind the Scenes | Life Below Zero
We are here to document the lives of people living in Alaska. The harsh reality is the environment we’re up against. It makes it tough to do our job. Working on Life Below Zero can be very dangerous. Guns here, cameras; you never know what to expect. You …