Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython break statement

Python break statement

Python break is used to terminate the execution of the loop. 

Python break statement Syntax:

Loop{
    Condition:
        break
    }

Python break statement

break statement in Python is used to bring the control out of the loop when some external condition is triggered. break statement is put inside the loop body (generally after if condition).  It terminates the current loop, i.e., the loop in which it appears, and resumes execution at the next statement immediately after the end of that loop. If the break statement is inside a nested loop, the break will terminate the innermost loop.

Break-statement-python 

Example of Python break statement

Example 1: 

Python3




for i in range(10):
    print(i)
    if i == 2:
        break


Output:

0
1
2

Example 2: 

Python3




# Python program to
# demonstrate break statement
  
s = 'neveropen'
# Using for loop
for letter in s:
  
    print(letter)
    # break the loop as soon it sees 'e'
    # or 's'
    if letter == 'e' or letter == 's':
        break
  
print("Out of for loop"    )
print()
  
i = 0
  
# Using while loop
while True:
    print(s[i])
  
    # break the loop as soon it sees 'e'
    # or 's'
    if s[i] == 'e' or s[i] == 's':
        break
    i += 1
  
print("Out of while loop ")


Output:

g
e
Out of for loop

g
e
Out of while loop

In the above example, both the loops are iterating the string ‘neveropen’ and as soon as they encounter the character ‘e’ or ‘s’, if the condition becomes true and the flow of execution is brought out of the loop.

Example 3:

Python3




num = 0
for i in range(10):
    num += 1
    if num == 8:
        break
    print("The num has value:", num)
print("Out of loop")


Output

The num has value: 1
The num has value: 2
The num has value: 3
The num has value: 4
The num has value: 5
The num has value: 6
The num has value: 7
Out of loop

In the above example, after iterating till num=7, the value of num will be 8 and the break is encountered so the flow of the execution is brought out of the loop.

Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore some statements of the loop before continuing further in the loop. These can be done by loop control statements called jump statements. Loop control or jump statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control/jump statements.

RELATED ARTICLES

Most Popular

Recent Comments