Will any additional code execute after a break statement?


#1

Question

In this exercise, a break statement is used as the last line in the for loop. If there was any additional code in the for loop after the break, would it execute?

Answer

No, the break statement will terminate the execution of the for loop. It does not allow for the execution of any additional code in the loop if it exists. In other words, break doesn’t stop the loop from completing any new iterations, it completely stops the current iteration at the point break is placed.

In the following example code, the print(counter) statement is called for numbers 1 through 4 but does not print the value 5.

counter = 0
while counter < 10:
    counter += 1
    if counter == 5:
        print("Reached 5")
        break
    print(counter)

#2

Extra Study

The break discussion doesn’t end there. It has a ‘case in tow’ which is else on the while.

while ...
    if ...: break
else:
    # loop completed successfully

Eg.

while counter < 10:
    counter += 1
    if randint(1,11) == 11:
        print ('Won!')
        break
else:
	print ('done')


# Won!

Whoo-hoo! we won with 11 on the first roll!

while counter < 10:
    counter += 1
    if randint(1,11) == 11:
        print ('Won!')
        break
else:
	print ('done')

	
# done

The loop completed and we’re all good. Nothing to report here.


This will come up at some point, so consider the above a pre-imersion not directly relating to this lesson, but akin to, as we will learn, upcoming.

Sidebar:

Begin the practice of using parens on print so it becomes nature. The transition to Python 3 will have less bumps if that is already in your kit.