Break and Continue statements
Updated on 28 Dec 2022
There are 2 important commands that can be used inside loops. continue and break.
break
The break command is used to ‘break’ out of a loop. Consider the following example:
total = 0
mylist = [10, 15, 18, 'brent', 8]
for v in mylist:
total = total + v
print('the total value is ' + str(total))
We actually get an error, which is not surprising because we are trying to add brent
to a number. Let’s assume that our solution is to add up all the numbers up to the first non-number that it encounters. We can then modify our code like this:
total = 0
mylist = [10, 15, 18, 'brent', 8]
for v in mylist:
if type(v) != int:
break
total = total + v
print('the total value is ' + str(total))
Tip: The type() is a built-in method of Python that returns the type of variable you have.
continue
The continue command goes back to the start of the loop and ‘continues’ with the next iteration. Imagine our previous example except this time we need to add up all the numbers. All we have to do is replace break with continue. What will happen is that when the loop comes to ‘brent’, it will go back to the start of the loop and increment to the next value.
Loops - guided exercise
Lets go back to our very first loop program, and modify it to use the break command.
Original
maxline = 5
counter = 0
process = True
while process:
counter = counter + 1
print('Hello line {0}'.format(counter))
if counter == maxline:
process = False
Modified
maxline = 5
counter = 0
while True:
counter = counter + 1
print('Hello line {0}'.format(counter))
if counter == maxline:
break