Execute Program

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 continue to 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 = 0

    while len(data) > 0:
    item = data.pop(0)
    if item < 0:
    continue
    result += item

    result
    Result:
    13Pass Icon
  • The break statement terminates the entire loop immediately. Execution moves to the next statement after the loop.

  • >
    data = [10, -1, 3]
    result = 0

    while len(data) > 0:
    item = data.pop(0)
    if item < 0:
    break
    result += item

    result
    Result:
    10Pass Icon
  • Be careful when using break! Normally, when we reach the end of a while loop, we know that its condition is now false.

  • >
    data = [20, 3, 2, -5, 3, 2]
    while len(data) > 0:
    data.pop()
    len(data)
    Result:
    0Pass Icon
  • In that example, the condition was len(data) > 0. At the end of the loop, data is empty, which makes the condition false.

  • When we break out of a while, 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 makes break slightly 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:
    break

    len(data)
    Result:
    2Pass Icon
  • The while's condition was len(data) > 0. But because of the break, data still had two elements after the loop ended.

  • We just showed continue and break in while loops, but they also work in for loops. The details are exactly the same: continue skips to the next loop iteration, and break immediately ends the entire loop.