M&C8: Using break and continue

Languages like Python typically have statements like break and continue.  While their use goes beyond the material covered in the CSE course, some students may find them and use them as they can be very convenient. We describe them so teachers understand their basic use.

The break statement exits (“breaks out”) a loop. The statements that follow the break statement in the loop will not be executed.  Break statements are often used to skip the rest of loop once the task is achieved.

Example 1: Searching for a value in a list. Suppose we want to search a list of numbers for the value 10. Once the target value is found, there is no need to continue with the loop.

MyList = [5, 3, 20, 7, 10, 5, 4, 1, 25, 9]
size = len(MyList)

for i in range(size):
	if MyList[i] == 10:
		print("Found it!", MyList[i])
		break

Moreover, a break statement is convenient in the situations when the condition terminating the loop is hard to express in a Boolean expression.  For example, one can write the loop as an infinite loop and break out of it when an if-statement determines the break out condition is satisfied. But make sure breaking out of the loops happens in all situations!

Example 2: The code below prompts the user to enter her password. The loop keeps on prompting for password until the correct password is entered.

while True:
	password = input("Enter Password ")
	if (password == "python"):
		break

The continue statement skips the remaining statements in the loop and moves to (continues) the next iteration of the loop.

Example 3: Print the letters of a word without printing any ‘a’s

word = "Indiana"
for letter in word:
	if letter == 'a':
		continue
	print (letter)