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.
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