10.4. Break and Continue

Break and continue are two ways to modify the behavior of for loops and while loops.

10.4.1. Break

In Python, the keyword break causes the program to exit a loop early. break causes the program to jump out of for loops even if the for loop hasn’t run the specified number of times.break causes the program to jump out of while loops even if the logical condition that defines the loop is still True.

An example using break in a for loop is below.

for i in range(100):
    print(i)
    if i == 3:
        break
print('Loop exited')
0
1
2
3
Loop exited

When the loop hits i=3, break is encountered and the program exits the loop.

An example using break in a while loop is below.

age= '-5'
while True:
    try:
        out = input('type q to exit the loop: ')
    except:
        out = 'q'
    if out == 'q':
        break
print('Loop exited')
Loop exited

10.4.2. Continue

In Python, the keyword continue causes the program to stop running code in a loop and start back at the top of the loop. Remember the keyword break cause the program to exit a loop. continue is similar, but continue causes the program to stop the current iteration of the loop and start the next iteration at the top of the loop.

A code section that uses continue in a for loop is below.

for i in range(4):
    if i==2:
        continue
    print(i)
0
1
3

When the code section is run, the number 2 is not printed. This is because when i=2 the program hits the continue statement. Therefore, the line print(i) isn’t run when i=2. Then the program starts back up at the start of the loop with the next number i=3.