Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Breaking Out of Loops and Blocks

The break statement is a handy way for exiting a loop from anywhere within the loop’s body. For example, here is an alternative way to sum an unknown number of numbers:

# donesum_break.py
total = 0
while True:
    s = input('Enter a number (or "done"): ')
    if s == 'done':
        break # jump out of the loop
    num = int(s)
    total = total + num
print('The sum is ' + str(total))

The while-loop condition is simply True, which means it will loop forever unless break is executed. The only way for break to be executed is if s equals 'done'.

A major advantage of this program over donesum.py is that the input statement is not repeated. But a major disadvantage is that the reason for why the loop ends is buried in the loop body. It’s not so hard to see it in this small example, but in larger programs break statements can be tricky to see. Furthermore, you can have as many breaks as you want, which adds to the complexity of understanding the loop.

Generally, it is wise to avoid the break statement, and to use it only when it makes your code simpler or clearer.

A relative of break is the continue statement: When continue is called inside a loop body, it immediately jumps up to the loop condition—thus continuing with the next iteration of the loop. It is a little less common than break, and generally it should be avoided altogether.

  • + Share This
  • 🔖 Save To Your Account