The break Statement
Sometimes you don't need to go through the whole loop. When you are looking for something and you find it, there is no reason to keep looking. The break statement ends the loop immediately, and the program continues with the code after the loop.
Let's find the first number from 100 up that is divisible by 7. The loop prints each number it checks, so that you can see where it stops:
for number in range(100, 200):
print("Checking", number)
if number % 7 == 0:
print("First multiple of 7:", number)
break
print("Done")Checking 100
Checking 101
Checking 102
Checking 103
Checking 104
Checking 105
First multiple of 7: 105
DoneThe condition number % 7 == 0 is true when the remainder after dividing by 7 is 0. When the loop gets to 105, the condition is true. The program prints the result, and break ends the loop: the numbers from 106 on are never checked, and the program goes on with print("Done"). Without break, the loop would run all the way to 199 and print 14 multiples of 7, not just the first one.
You will almost always put break inside an if. On its own, it would end the loop during its very first iteration. break works the same way in while and for loops.
Instructions
- 1
The list
temperaturesholds morning temperatures in the order they were measured. Write a loop that goes through it and, for every temperature below zero, printsFirst frost:and the temperature. Run the program: it prints three lines, but only the first one is right. - 2
Add
breakinside theif, after the printing, so that the loop stops at the first frost. Now onlyFirst frost: -3is printed.