Python From Beginner to Advanced

0% completed

Previous
Next
Python - break statement

The break statement in Python is used to exit a loop immediately when a certain condition is met. Instead of running until the loop’s condition becomes False, break forces the loop to stop and moves the execution to the next statement outside the loop. This is useful when we need to terminate a loop early.

Syntax

for variable in sequence: if condition: break # Stops the loop # Other statements inside the loop while condition: if condition: break # Stops the loop # Other statements inside the loop
  • break can be used inside both for and while loops.
  • When Python encounters break, it stops the loop immediately and moves to the next statement outside the loop.

Examples

Example 1: Stopping a "for" Loop

Python3
Python3

. . . .

Explanation

  1. The loop runs from 1 to 9.
  2. When num reaches 5, the if condition becomes True, and break stops the loop.
  3. In the output, numbers from 1 to 4 will be printed, and the loop will stop at 5.

Example 2: Stopping a "while" Loop

Python3
Python3

. . . .

Explanation

  1. The loop starts from 1 and increases count by 1 in each iteration.
  2. When count reaches 6, the condition becomes True, and break stops the loop.
  3. In the output, numbers from 1 to 5 will be printed, and the loop will stop at 6.

The break statement is used to exit loops early when a specific condition is met. It works in both for and while loops and helps improve efficiency by avoiding unnecessary iterations. Instead of letting the loop run until its condition becomes False, break forces an immediate stop.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next