Today we’ll be talking about the break statement.
Loops work as long as there are still elements to be iterated over in a collection (the for loop) or a condition is met (the while loop). But sometimes we want to leave a loop earlier. We can do it using the break statement. This statement breaks the loop immediately:
target = 10
guess = 0
while guess != target:
guess = int(input("Choose a number 1-20 or press 0 and Enter to quit: "))
if guess == 0:
break
if guess == target:
print("You win!")
else:
print("Try again!")
In this short program we enter a number. The loop runs as long as our guess is not equal to 10, which is the target number. But we also can leave this fascinating game earlier just by pressing 0. So, the program first checks if our input was 0. If it was, it hits the break statement and the loop stops. In this case the whole program stops because there’s nothing more after the loop, but if there were, it’d jump to the next line of code after the loop.
Here’s what the output might look like:
Choose a number 1-20 or press 0 and Enter to quit: 2
Try again!
Choose a number 1-20 or press 0 and Enter to quit: 5
Try again!
Choose a number 1-20 or press 0 and Enter to quit: 0
break in Nested Loops
If the break statement is inside a nested loop, it stops the execution of the innermost loop. By the way, we can nest any type of loop inside any type of loop, so we can have while loops inside while loops, for loops inside for loops, but also while loops inside for loops and vice versa. Here’s an example with a break statement in the nested for loop:
while counter < 3:
print("Round " + str(counter))
for i in range(4):
if i == 2:
break
print(i)
counter += 1
print()
And here’s the output:
Round 0
0
1
Round 1
0
1
Round 2
0
1
In the above code the break statement is inside the inner for loop. It stops the for loop and goes on to the next statement after the for loop, which is counter += 1 and then execution continues with the rest of this iteration of the outer while loop. When it reaches the end of the while loop, it checks the condition in the while loop and if it’s still true, it starts the next iteration. Each time when the break statement is reached, execution leaves the for loop. That’s why the for loop never makes it to print all the four numbers as it is supposed to do.