0
0
Pythonprogramming~5 mins

Break statement behavior in Python

Choose your learning style9 modes available
Introduction

The break statement stops a loop early when you want to exit before it finishes all steps.

When searching for a specific item in a list and you want to stop once found.
When reading input until a certain condition is met and then stop.
When looping through options but want to exit as soon as a valid choice is detected.
Syntax
Python
break

The break statement is used inside loops like for or while.

It immediately stops the loop and moves to the code after the loop.

Examples
This loop prints numbers 0, 1, 2 and stops when i is 3.
Python
for i in range(5):
    if i == 3:
        break
    print(i)
This loop keeps asking for input until the user types 'exit'.
Python
while True:
    answer = input('Type exit to stop: ')
    if answer == 'exit':
        break
Sample Program

This program prints numbers from the list until it finds 5, then stops the loop and prints 'Loop ended'.

Python
numbers = [1, 3, 5, 7, 9]
for num in numbers:
    if num == 5:
        break
    print(num)
print('Loop ended')
OutputSuccess
Important Notes

Break only stops the innermost loop it is inside.

Using break can make your program faster by avoiding unnecessary steps.

Summary

The break statement stops a loop immediately.

It is useful to exit loops early when a condition is met.

Break works inside for and while loops.