Loops, and where your data lives

INPUT · Slides

Stopping early, and skipping one go

01 / 07

Wanting to stop partway

You are going down a list of scores and you want to stop as soon as one person has passed. There is no point looking at the rest.

The word that calls a loop off partway is break.

02 / 07

The shape of break

break is a line all by itself. When it runs, it leaves the loop there and then and carries on at the lines that are not indented.

In the example below it leaves at the point i becomes 3, so no 3 is shown. It says range(10) and yet it only went round three times.

for i in range(10):    if i == 3:        break    print(i)print("done")

Result

0
1
2
done

03 / 07

The find-it-and-finish shape

break is at its best when you are looking for something. Once you have what you came for, there is no need to see any further.

The example below calls it off the moment "orange" turns up. "grape" never even gets looked at.

for fruit in ["apple", "orange", "grape"]:    print(fruit)    if fruit == "orange":        break

Result

apple
orange

04 / 07

continue skips just that one go

The other word is continue, and this one does not end the loop.

It abandons the rest of that go and moves on to the next. In the example below only the print for 2 is skipped; 3 and 4 come out as usual.

for i in range(5):    if i == 2:        continue    print(i)

Result

0
1
3
4

05 / 07

The difference between the two

They look alike and what they do is nothing alike.

  • break … ends the loop itself. It never comes back
  • continue … cuts short that one go. The next one still runs

"No further use for this" means break; "pass on this one" means continue. If you cannot decide, ask whether you have any use for the goes that follow.

06 / 07

Putting while and break together

break works in a while too, letting you order an ending from inside that would be awkward to write as a condition.

One warning, though. Lean on break too hard and it becomes difficult to see where the loop ends. If the condition can say it plainly, let it.

number = 0while number < 100:    print(number)    if number == 2:        break    number += 1

Result

0
1
2

07 / 07

It is also a tool for keeping indents shallow

continue brings one more benefit with it.

Wrap "do nothing in this case" in an if and everything that follows sinks a level deeper. Throw it out early with continue and the rest of the work can stay where it was.

Handy, but too much of either makes the flow hard to follow. One per loop is a fair guide.