Chapter 5: Breaking the flow

break

face Josiah Wang

You may have previously struggled a bit with trying to elegantly exit a loop, especially when you have fulfilled some criteria early on.

For example, below is my implementation of the exhaustive search algorithm for square root from earlier. Do you find it hard to read and to understand?

1
2
3
4
5
6
7
8
9
n = int(input("Please enter a number: "))
x = 0
found = False
while not found and x <= n:
    if abs(x*x - n) < 0.00001:
        print(x)
        found = True
    else:
        x = x + 0.0001

Compare the code above to the one below. The break statement (Line 6) will force your program to exit the nearest loop. In this case, it will bring your program straight to Line 10. Do you feel that it is easier to read than the above?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
n = int(input("Please enter a number: "))
x = 0
while x <= n:
    if abs(x*x - n) < 0.00001:
        print(x)
        break

    x = x + 0.0001

print("Exiting program...")

The break statement allows you to make a ‘quick exit’ from a loop. You will tend to use it with an if statement. When your program interpreter hits a break statement, it will forcefully ‘break out’ from the nearest loop you are currently in.