Exiting loops with break

Many programming languages support a loop construct which places the predicate test at the end of the loop rather than at the beginning. For example, C, C++, C# and Java support the do-while construct. Other languages have repeat-until loops instead or as well. This is not the case in Python, where the idiom is to use while True together with an early exit, facilitated by the break statement.

The break statement jumps out of the loop — and only the innermost loop if severals loops have been nested — continuing execution immediately after the loop body.

Let's look at an example of break, introducing a few other Python features along the way, and examine it line-by-line:

>>> while True:
... response = input()
... if int(response) % 7 == 0:
... break
...

We start with a while True: for an infinite loop. On the first statement of the while block we use the built-in input() function to request a string from the user. We assign that string to a variable called response.

We now use an if-statement to test whether the value provided is divisible by seven. We convert the response string to an integer using the int() constructor and then use the modulus operator, %, to divide by seven and give the remainder. If the remainder is equal to zero, the response was divisible by seven, and we enter the body of the if-block.

Within the if-block, now two levels of indentation deep, we start with eight spaces and use the break keyword. break terminates the inner-most loop — in this case the while-loop — and causes execution to jump to the first statement after the loop.

Here, that statement is the end of the program. We enter a blank line at the three dots prompt to close both the if-block and the while-block. Our loop will start executing, and will pause at the call to input() waiting for us to enter a number. Let's try a few:

12
67
34
28
>>>

As soon as we enter a number divisible by seven the predicate becomes True, we enter the if-block, and then we literally break out of the loop to the end of program, returning us to the REPL prompt.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset