Python Tutorials

Python Programs

Python Break Statement


Python Break Statement

In this tutorial, we will learn about the break statement in Python. We will cover the basics of using the break statement to exit loops prematurely.


What is a Break Statement

A break statement is used to terminate the execution of a loop. When a break statement is encountered, the loop immediately terminates, and the program continues with the next statement following the loop.


Syntax

The syntax for the break statement in Python is:

break

The break statement can be used in for, while, and do-while loops to exit the loop prematurely.



Exiting a For Loop Early

  1. Use a for loop to iterate over a range of numbers from 1 to 10.
  2. Inside the loop, use an if statement to check if the current number is equal to 5.
  3. If the condition is true, use a break statement to exit the loop.
  4. Print the current number.

Python Program

for i in range(1, 11):
    if i == 5:
        break
    print(i)

Output

1
2
3
4


Exiting a While Loop Early

  1. Declare a variable i and initialize it to 1.
  2. Use a while loop to iterate while i is less than or equal to 10.
  3. Inside the loop, use an if statement to check if i is equal to 5.
  4. If the condition is true, use a break statement to exit the loop.
  5. Print the value of i.

Python Program

i = 1
while i <= 10:
    if i == 5:
        break
    print(i)
    i += 1

Output

1
2
3
4


Exiting a Nested Loop

  1. Use nested loops to iterate over rows and columns of a 2D array.
  2. Inside the nested loops, use an if statement to check if a specific condition is met.
  3. If the condition is true, use a break statement to exit both loops.

Python Program

for i in range(3):
    for j in range(3):
        print(f'({i}, {j})')
        if i == j == 1:
            break

Output

(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)