1.3.2 loops, continue, and break

Next, let’s quickly revisit loops in Python. There are two kinds of loops in Python, the for-loop and the while-loop. You should know that the for-loop is typically used when the goal is to go through a given set, or list of items, or do something a certain number of times. In the first case, the for-loop typically looks like this

for item in list: 
    # do something with item 

while in the second case, the for-loop is often used together with the range(…), len(...), or enumerate(...) functions to determine how many times the loop body should be executed:

for i in range(50):  
	# do something 50 times

In contrast, the while-loop has a condition that is checked before each iteration and if the condition becomes False, the loop is terminated and the code execution continues to the next line after the loop body. With this knowledge, it should be pretty clear what the following code example does:

import random 

r = random.randrange(100) # produce random number between 0 and 99 
attempt_count = 1 

while r != 11: 
    attempt_count += 1 
    r = random.randrange(100) 
print(f'This took {attempt_count} attempts')

There are two additional commands, break and continue, that can be used in combination with either a for-loop or a while-loop. The break command will automatically terminate the execution of the current loop and continue with the next line of code outside of the loop. If the loop is part of a nested loop, only the inner (nested) loop will be terminated and the outer loop will progress to its next execution. This means we can rewrite the program from above using a for-loop rather than a while-loop like this:

import random 

attempt_count = 0 

for i in range(1000):  
    r = random.randrange(100) 
    attempt_count += 1 
    
    if r == 11: 
        break  # terminate loop and continue after it 

print(f'This took {attempt_count} attempts')

When the random number produced in the loop body is 11, the conditional if-statement will equate to True. The break command will be executed and the program execution immediately leaves the loop and continues with the print statement after it.

If you have experience with programming languages other than Python, you may know that some languages have a "dowhile" loop construct where the condition is only tested after each time the loop body has been executed so that the loop body is always executed at least once. Since we first need to create a random number before the condition can be tested, this example would actually be a little bit shorter and clearer using a do-while loop. Python does not have a built in do-while loop, but it can be simulated using a combination of while and break:

import random

attempt_count = 0  

while True: 
    r = random.randrange(100) 
    attempt_count += 1 

    if r == 11: 
        break 

print(f'This took {attempt_count} attempts') 

A while loop with the condition True will in principle run forever. However, since we have the if-statement with the break, the execution will be terminated as soon as the random number generator rolls an 11.

When a continue command is encountered within the body of a loop, the current execution of the loop body is also immediately stopped. In contrast to the break command, the execution then continues with the next iteration of the loop body. Of course, the next iteration is only started if the while condition is still True in the case of a while-loop. In the case of a for-loop, it will continue if there are still remaining items in the iterable that we are looping through. To demonstrate this, the following code goes through a list of numbers and prints only those numbers that are divisible by 3 (without remainder).

l = [3, 7, 99, 54, 3, 11, 123, 444] 

for n in l: 
    if n % 3 != 0:   # test whether n is not divisible by 3 without remainder 
        continue 

    print(n)

This code uses the built-in modulo operator % to get the remainder of the division of n and 3 in line 5. If this remainder is not 0, the continue command is executed and the next item in the list is tested. If the condition is False (meaning the number is divisible by 3 without a remainder), the execution continues as normal after the if-statement and prints the number.

As you saw in these examples, there are often multiple ways in which the loop constructs for, while, and control commands break, continue, and if-else can be combined to achieve the same result. While break and continue can be useful commands, they can also make code more difficult to read and understand. Therefore, they should only be used sparingly and when their usage leads to a simpler and more comprehensible code structure than a combination of for /while and if-else would do.