Site icon TestingDocs.com

Python break Statement

Overview

The Python break statement terminates a loop immediately when a certain condition (or conditions) is evaluated as true. It can be used in both for and while loops.

When nested loops are used in a program, and if a break encounters in the inner loop, then if terminates the inner loop, and execution control goes to the outer loop. On the other hand, if a break statement occurs in a single loop, then it transfers the execution control to the statement immediately after the loop.

Python break statement

The break statement terminates the nearest enclosing loop, skipping the optional else clause if the loop has one. The loop control target keeps its current value if a break statement terminates a for loop. When break passes control out of a try statement with a finally clause, that finally clause is executed before leaving the loop.

Syntax

The general syntax of the break statement is as follows:

break

The break may only occur syntactically nested in a for or while loop but not nested in a function or class definition within that loop.

Example

Python program to illustrate the break statement in a for loop.

 

############################################################
# This program to demo the usage of the break statement
# Python Tutorials - www.TestingDocs.com
############################################################
for i in range(1,10):
    if i==7:
        break
    print(i)
print("Exit for Loop")

 

Output

1
2
3
4
5
6
Exit for Loop

The range of the for loop is set to 1 through 10. When the if statement encounters loop variable i with value 7, the break statement gets executed, and the control transfers out of the for loop. The program only prints 1,2,3,4,5,6, and the “Exit for Loop”.

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website:

https://www.python.org

Exit mobile version