Python for Programmers: Terminating Loops
Welcome to the Terminating Loops lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Inside of a loop, you can use
continueto abort a single iteration. Execution immediately jumps back up to the loop's condition, which is checked again as usual.>
data = [10, -1, 3]result = 0while len(data) > 0:item = data.pop(0)if item < 0:continueresult += itemresultResult:
13
The
breakstatement terminates the entire loop immediately. Execution moves to the next statement after the loop.>
data = [10, -1, 3]result = 0while len(data) > 0:item = data.pop(0)if item < 0:breakresult += itemresultResult:
10
Be careful when using
break! Normally, when we reach the end of awhileloop, we know that its condition is now false.>
data = [20, 3, 2, -5, 3, 2]while len(data) > 0:data.pop()len(data)Result:
0
In that example, the condition was
len(data) > 0. At the end of the loop,datais empty, which makes the condition false.When we
breakout of awhile, we no longer have that guarantee. At first glance, we might incorrectly assume that the loop's condition is false after the loop ends. This makesbreakslightly dangerous.>
data = [20, 3, 2, -5, 3, 2]while len(data) > 0:# Remove the first element in the list.item = data.pop(0)if item < 0:breaklen(data)Result:
2
The
while's condition waslen(data) > 0. But because of thebreak,datastill had two elements after the loop ended.We just showed
continueandbreakinwhileloops, but they also work inforloops. The details are exactly the same:continueskips to the next loop iteration, andbreakimmediately ends the entire loop.