
Three more commands/concepts discussed in Chapter 2 of Automate the Boring Stuff with Python are break statements, continue statements and methods of ending a program that’s caught in a loop.
Break Statements
A break statement causes a program to immediately exit a loop’s block of code and go to the first line of code outside of that block. For example, the following program causes the computer to endlessly search for Dane McGowan. Once Dane is found, the program’s wait (and the loop) can come to an end.
while True:
print('With whom do I have the pleasure of speaking?')
name = input()
if name == 'Dane McGowan':
break
print('You are not the one we seek.')
print('''We've been waiting for you, ''' + name)
Continue Statements
A continue statement restarts a loop – I know, why didn’t they just name it restart? The following program searches for Dane just like the one above. It also uses a break statement to exit. Without the statement, it would be stuck in a loop and never know if it had, indeed, found who it sought (try it, comment out the break).
while True:
print('With whom do I have the pleasure of speaking?')
name = input()
if name != 'Dane McGowan':
print('You are not the one we seek.')
continue
break
print('''We've been waiting for you, ''' + name)
Ending a Program
Sometimes, a program can get caught in a loop. This means that it keeps repeating a command with no way for the user to escape via available input methods. Its the digital version of living through Groundhog Day.
password = ''
while password != '''Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn''':
print('Ia! Enter password to continue:')
password = input()
print('Iä! Iä! Cthulhu fhtagn!')
If the above program is run, the computer will keep asking the user for a password until the correct one is entered. Most people won’t be able to spell the right password on their first try, or maybe even their 100th, causing them to get stuck in a loop asking for a password that they can’t type correctly.
To end the program prematurely, and gain freedom from the loop, the user can press Control-C on the keyboard and manually break out of the loop and the program entirely. This is actually an old command, and the manual break is known to work in many command-line or shell programs – back in the 1980s and 1990s, I used it all the time to get out of DOS applications!
Lesson 6 (while loops, and the break and continue statements):
jk