Break Statement—Python

I’ve done a few posts now on loops. To review, Python has two kinds of loops: while loops and for loops.

I can think of plenty of times that we want to create an infinate loop. To review, an infintate loop is a loop that never ends. Consider this code.

while True:
    pass

Should you run this code, the program will never terminate because the loop condition is always True. In many cases, infinate loops are the result of programming errors, but let’s consider a menu driven program like this:

while True:
    print('1) New File')
    print('2) Open File')
    print('3) Save File')
    print('4) Exit...')

    choice = input('Enter choice => ')
    if choice == 1:
        pass # do something with a new file
    elif choice == 2:
        pass # do something to open a file
    elif choice == 3:
        pass # do something to save a file
    elif choice == 4:
        break # exit this loop and end the application

In this case, we want the program to program to continue to repeat this main menu until the user enters 4. That’s where the magic break keyword comes into play.

The break keyword liternally means to break out of a loop. This example is a common application of the loop but it doesn’t always have to be used in infinate loops. Let’s try and example with the for loop.

names = ['Bob Belcher',
         'Linda Belcher',
         'Louise Belcher',
         'Tina Belcher',
         'Gene Belcher']

bob = ''
for name in names:
    if 'Bob' in name:
        bob = name
        break   # There's no need to keep looping through
                # the rest of the list because we have found Bob
Advertisement

One thought on “Break Statement—Python”

  1. Thanks, I have just been searching for information approximately this topic for ages and yours is the greatest I have came upon so far. However, what concerning the conclusion? Are you positive concerning the supply?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: