Nearby lessons

49 of 159

Python - Break Statement

📌 What You Will Learn
  • Define the break statement and what it does to a loop
  • Identify break, continue and pass as the three transfer statements
  • Write a for loop that stops when a condition is met using break
  • Use break to exit an infinite while loop
  • Compare break with continue

Transfer Statements

Transfer statements are used to change the normal flow of program execution.

Python provides three transfer statements:

  • break
  • continue
  • pass

break Statement

The break statement is used to stop the loop immediately.

When Python executes the break statement, the loop terminates and control moves to the first statement after the loop.

Syntax

🐍Code Cell
1for variable in sequence:
2 if condition:
3 break
Output
No output captured.

Example 1 - break Statement

🐍Code Cell
1for i in range(10):
2 if i == 7:
3 break
4 print(i)
Output
0
1
2
3
4
5
6

Explanation

The loop starts from 0.

When i becomes 7, the break statement is executed.

The loop stops immediately.

Example 2 - break with while Loop

🐍Code Cell
1x = 1
2 
3while True:
4 print(x)
5 
6 if x == 5:
7 break
8 
9 x = x + 1
Output
1
2
3
4
5

Real World Usage of break

The break statement is commonly used in:

  • Search operations
  • Menu-driven programs
  • Password verification
  • Infinite loops that need an exit condition

Difference Between break and continue

break continue
Terminates the loop. Skips only the current iteration.
Control comes outside the loop. Control moves to the next iteration.
Remaining iterations are not executed. Remaining iterations continue normally.
📝 Key Takeaways
  • The break statement stops a loop immediately
  • After break, control moves to the first statement after the loop
  • break is used in search operations, menu-driven programs and password verification
  • break terminates the loop while continue skips only the current iteration
  • Remaining iterations are not executed after break

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2