Python break statement

Using loops in Python automates and repeats tasks efficiently. But sometimes a condition may arise where you want to exit the loop completely, skip the iteration, or ignore this condition. This can be done with loop control statements . Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects created in that scope are destroyed. Python supports the following control statements.

  • Continue statement
  • Break statement
  • Go through statement

In this article the focus will be on the break statement.

Break statement

The Python break statement is used to take a control out of a loop when some external condition is triggered. The break statement is placed inside the body of the loop (usually after the if condition).

Syntax :

 break 

Example :

# Python program for
# demonstrate break statement

 

s = `pythonengineering`

# Usage for loop

for letter in s:

 

print (letter)

< code class = "undefined spaces">  # break the loop as soon as it sees "e"

  # or & # 39; s & # 39;

if letter = = `e` or letter = = `s` :

break

 

print ( "Out of for loop" )

print ()

 

i = 0

 
# Using the while loop

while True :

print (s [i])

 

# break the loop as soon as it sees "e"

# or & # 39; s & # 39;

  if s [i] = = `e` or s [i] = = `s` :

  break

i + = 1

 

print ( "Out of while loop" )

Exit :

 ge Out of for loop ge Out of while loop 

In the above example, both loops iterate over the line “pythonengineering”, and as soon as they meet the character “e” or “s”, the if condition becomes true, and the thread is exited from the loop.