python
  1. python-break

Python Break Statement

The break statement in Python is used to immediately terminate a loop when a certain condition is met. It is used inside loops like for and while to stop the iteration when a condition is satisfied. It helps in avoiding unnecessary iterations once we have found what we were looking for.

Syntax

while expression:
    if condition:
        break

Example

# program to find the first odd number in a list
lst = [2, 4, 6, 7, 8, 10, 11]
for i in lst:
    if i % 2 != 0:
        print("The first odd number is", i)
        break

Output

The first odd number is 7

Explanation

The above program uses a for loop to iterate through each number in the list lst. When it encounters an odd number, the program prints the message "The first odd number is" followed by the odd number and then terminates the loop using the break statement.

Use

The break statement is mainly used to terminate loops. It can be used in situations where we need to stop iterating once we have found what we were looking for. This saves time and computation as it prevents the program from making unnecessary iterations.

Important Points

  • The break statement terminates the current loop only.
  • It is usually used in combination with an if statement to check for a specific condition and stop the iteration.
  • If it is used inside nested loops (i.e. a loop inside another loop), it only terminates the innermost loop.

Summary

In summary, the break statement is a useful tool in Python when we need to stop iterating through a loop once a particular condition is met. It terminates the loop in which it is called and allows the program to move on to the next part of the code.

Published on: