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

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

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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.