3-1-3-25. Break, Continue

sometimes need more precise control over when a loop should end.

In these cases, we use the break keyword.

A loop will terminate immediately if it encounters a break statement.

We can use this to end the loop if we detect that some condition has been met.

The break keyword can be used in both for and while loops.

For example, suppose you want to load a cargo ship with a list of items called manifest.

This list contains tuples of items and their weights.

Ideally, you would like to load all the items on

the ship but the ship has a maximum weight capacity.

Therefore, when the ship’s capacity is reached,

you want to stop loading.

To accomplish this, let’s use a for loop loading

each item and keeping track of the weight of all the items we have loaded so far.

Here, we check if the ship’s total cargo weight reaches

its maximum capacity of 100 with each addition of cargo.

If it does, we use a break statement to stop loading.

If not, we load the next item and add on its weight.

Here’s what we end up loading.

That’s not good.

The boat is severely over its weight limit of 100.

The break statement did prevent us from putting every item on

the boat but we still exceeded the limit by 111.

It’s difficult to see what’s gone wrong.

One strategy we can use is to add print statements in the code.

This is a really handy technique as it can give us some insight

into what happens in the code as it’s running step-by-step.

Having print statements frequently that give context can

really assist us in understanding what went wrong here.

Here’s the loop with debugging statements added.

Debugging is the process of identifying and removing errors in your code.

Here, we can see that we didn’t break until the weight exceeded 100,

when really, we should break before that item is added.

Additionally, we can see that the cheeses still could

have fit if the machine wasn’t added.

This brings us to another statement.

Sometimes, rather than breaking out of the loop completely,

there will be times we want to skip simply one iteration of the loop.

In this case, we would use the continue keyword.

In this example, we iterate through a list of

foods and increment account if the food is a fruit.

Here, we terminate an iteration if the food is not found in fruit.

Otherwise, we add one to fruit count.

So when food is hummus or toast in this loop,

the rest of the loop is completely skipped.

For 루프는 시퀀스의 모든 요소를 ​​반복합니다.

while 루프는 중지 조건이 충족될 때까지 반복합니다.

이것은 대부분의 목적에 충분하지만 우리는

루프가 종료되어야 하는 시점에 대한 보다 정확한 제어가 필요할 때가 있습니다.

이 경우 break 키워드를 사용합니다.

break 문을 만나면 루프가 즉시 종료됩니다.

어떤 조건이 충족되었음을 감지하면 이것을 사용하여 루프를 종료할 수 있습니다.

break 키워드는 for 및 while 루프 모두에서 사용할 수 있습니다.

예를 들어, 매니페스트라는 항목 목록이 있는 화물선을 싣고 싶다고 가정합니다.

이 목록에는 항목의 튜플과 해당 가중치가 포함됩니다.

이상적으로는 모든 항목을

그러나 배는 최대 중량 용량을 가지고 있습니다.

따라서 선박의 용량에 도달하면

로드를 중지하고 싶습니다.

이를 수행하기 위해 for 루프 로딩을 사용합시다.

각 항목을 확인하고 지금까지 로드한 모든 항목의 무게를 추적합니다.

여기서 우리는 선박의 총 화물 중량이

화물을 추가할 때마다 최대 100개까지 수용할 수 있습니다.

그렇다면 break 문을 사용하여 로드를 중지합니다.

그렇지 않은 경우 다음 항목을 로드하고 가중치를 추가합니다.

다음은 우리가 로드할 내용입니다.

그 좋지 않다.

보트는 무게 제한인 100을 크게 초과했습니다.

break 문으로 인해 모든 항목을 넣을 수 없었습니다.

보트이지만 우리는 여전히 111로 제한을 초과했습니다.

무엇이 잘못되었는지 보기가 어렵습니다.

우리가 사용할 수 있는 한 가지 전략은 코드에 print 문을 추가하는 것입니다.

이것은 우리에게 통찰력을 줄 수 있으므로 정말 편리한 기술입니다.

코드가 단계별로 실행될 때 어떤 일이 발생하는지 설명합니다.

컨텍스트를 제공하는 print 문을 자주 사용하면

여기서 무엇이 잘못되었는지 이해하는 데 정말 도움이 됩니다.

다음은 디버깅 문이 추가된 루프입니다.

디버깅은 코드에서 오류를 식별하고 제거하는 프로세스입니다.

여기서 우리는 무게가 100을 넘을 때까지 깨지지 않았음을 알 수 있습니다.

정말로, 우리는 그 항목이 추가되기 전에 중단되어야 합니다.

또한 치즈가 여전히

기계가 추가되지 않은 경우 적합합니다.

이것은 우리를 또 다른 진술로 이끕니다.

때로는 루프에서 완전히 벗어나기 보다는

루프의 한 번의 반복을 건너뛰고 싶을 때가 있을 것입니다.

이 경우 계속 키워드를 사용합니다.

이 예에서는 다음 목록을 반복합니다.

식품 및 식품이 과일인 경우 증분 계정.

여기에서 음식이 과일에서 발견되지 않으면 반복을 종료합니다.

그렇지 않으면 과일 수에 하나를 추가합니다.

따라서 이 루프에서 음식이 후무스나 토스트일 때,

나머지 루프는 완전히 건너뜁니다.

Break, Continue

Sometimes we need more control over when a loop should end, or skip an iteration. In these cases, we use the break and continue keywords, which can be used in both for and while loops.

  • break terminates a loop
  • continue skips one iteration of a loop

Watch the video and experiment with the examples below to see how these can be helpful.

Try It Out!

Below, you’ll find two methods to solve the cargo loading program from the video. The first one is simply the one found in the video, which breaks from the loop when the weight reaches the limit. However, we found several problems with this. The second method addresses these issues by modifying the conditional statement and adding continue. Run the code below to see the results and feel free to experiment!

manifest = [("bananas", 15), ("mattresses", 24), ("dog kennels", 42), ("machine", 120), ("cheeses", 5)]

# the code breaks the loop when weight exceeds or reaches the limit
print("METHOD 1")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
    print("current weight: {}".format(weight))
    if weight >= 100:
        print("  breaking loop now!")
        break
    else:
        print("  adding {} ({})".format(cargo_name, cargo_weight))
        items.append(cargo_name)
        weight += cargo_weight

print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))

# skips an iteration when adding an item would exceed the limit
# breaks the loop if weight is exactly the value of the limit
print("\nMETHOD 2")
weight = 0
items = []
for cargo_name, cargo_weight in manifest:
    print("current weight: {}".format(weight))
    if weight >= 100:
        print("  breaking from the loop now!")
        break
    elif weight + cargo_weight > 100:
        print("  skipping {} ({})".format(cargo_name, cargo_weight))
        continue
    else:
        print("  adding {} ({})".format(cargo_name, cargo_weight))
        items.append(cargo_name)
        weight += cargo_weight

print("\nFinal Weight: {}".format(weight))
print("Final Items: {}".format(items))
%d