break and continue statement in Python

break statement #

The break statement is used to terminate the loop prematurely when certain condition is met. When break statement is encountered inside the body of the loop, the current iteration stops and program control immediately jumps to the statements following the loop. The break statement can be written as follows:

break

The following examples demonstrates break statement in action.

Example 1:

python101/Chapter-11/break_demo.py

for i in range(1, 10):
    if i == 5:  # when i is 5 exit the loop
        break
    print("i =", i)

print("break out")

Output:

i = 1
i = 2
i = 3
i = 4
break out

As soon as the value of i is 5, the condition i == 5 becomes true and the break statement causes the loop to terminate and program controls jumps to the statement following the for loop. The print statement in line 6 is executed and the program ends.

Example 2:

The following programs prompts the user for a number and determines whether the entered number is prime or not.

python101/Chapter-11/prime_or_not.py

num = int(input("Enter a number: "))

is_prime = True

for i in range(2, num):
    if num % i == 0:
        is_prime = False  # number is not prime
        break  # exit from for loop

if is_prime:
    print(num, "is prime")
else:
    print(num, "is not a prime")

First Run Output:

Enter a number: 11
11 is prime

Second Run Output:

Enter a number: 23
23 is prime

Third Run Output:

Enter a number: 6
6 is not a prime

A prime number is a number which is only divisible by 1 or by itself. Here are some examples of prime numbers:

1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 33, 37, 41

A number n is prime, if it is not divisible by any number from 2 to n-1. Consider the following examples:

Example 1:

Is 5 a prime number ?

Here are steps to determine whether the number 5 is prime or not.

Question Programming Statement Result
Is 5 divisible by 2 ? 5 % 2 == 0 False
Is 5 divisible by 3 ? 5 % 3 == 0 False
Is 5 divisible by 4 ? 5 % 4 == 0 False

Result: 5 is prime

Example 2:

Is 9 a prime number ?

Here are steps to determine whether number 9 is prime or not.

Question Programming Statement Result
Is 9 divisible by 2 ? 9 % 2 == 0 False
Is 9 divisible by 3 ? 9 % 3 == 0 True

In the second step our test 9 % 3 == 0 passed. In other words, 9 is divisible by 3, that means 9 is not a prime number. At this point, it would be pointless to check divisibility of 9 by the remaining numbers. So we stop.

This is exactly what we are doing in the above program. In line 1, We ask the user to enter a number. In line 3, we have declared a variable is_prime with bool value True. In the end, this variable will determine whether the number entered by the user is prime or not.

The for loop iterates through 2 to num-1. If num is divisible (line 6) by any number within this range, we set is_prime to False and break out of the for loop immediately. However, if the condition n % i == 0 never satisfies the break statement will not be executed and is_prime will remain set to True. In which case num will be a prime number.

break statement inside nested loop #

In a nested loop the break statement only terminates the loop in which it appears. For example:

python101/Chapter-11/break_inside_nested_loop.py

for i in range(1, 5):    
    print("Outer loop i = ", i, end="\n\n")
    for j in range (65, 75):
        print("\tInner loop chr(j) =", chr(j))
        if chr(j) == 'C':
            print("\tbreaking out of inner for loop ...\n")
            break

    print('-------------------------------------------------')

Output:

Outer loop i =  1

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------
Outer loop i =  2

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------
Outer loop i =  3

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------
Outer loop i =  4

        Inner loop chr(j) = A
        Inner loop chr(j) = B
        Inner loop chr(j) = C
        breaking out of inner for loop ...

-------------------------------------------------

For every iteration of the outer loop, the inner for loop is executed thrice. As soon as, the condition chr(j) == 'C' satisfies the break statement causes an immediate exit from the inner for loop. However, the outer for loop will keep executing as usual.

continue statement #

The continue statement is used to move ahead to the next iteration without executing the remaining statement in the body of the loop. Just like break statement, continue statement is commonly used in conjunction with a condition. The continue statement can be written as follows:

continue

Here is an example to demonstrate the working of the continue statement:

python101/Chapter-11/continue_demo.py

for i in range(1, 10):
    if i % 2 != 0:
        continue
    print("i =", i)

Output:

i = 2
i = 4
i = 6
i = 8

In the above program when the condition i % 2 != 0 evaluates to True, the continue statement is executed and execution of print() function inside the body of the loop is omitted, and program control moves ahead to the next iteration of the loop.

We can also use break and continue statement together in the same loop. For example:

python101/Chapter-11/break_and_continue.py

while True:
    value = input("\nEnter a number: ")

    if value == 'q':  # if input is 'q' exit from the while loop
        print("Exiting program (break statement executed)...")
        break

    if not value.isdigit():  # if input is not a digit move on to the next iteration
       print("Enter digits only (continue statement executed)")
       continue

    value = int(value)
    print("Cube of", value, "is", value**3)  # everything is fine, just print the cube

Output:

Enter a number: 5
Cube of 5 is 125

Enter a number: 9
Cube of 9 is 729

Enter a number: @#
Enter digits only (continue statement executed)

Enter a number: 11
Cube of 11 is 1331

Enter a number: q
Exiting program (break statement executed)...

The above program asks the user to enter a number and calculates it's cube. If a number is entered the program displays the cube of the number. If the user enters a enter a non digit character then the continue statement is executed and the execution of remaining statements in the body of the loop is skipped and the program asks the user again for the input. On the other hand, If the user enters q then the break statement inside the loop body is executed and the while loop terminates.