python break out of function

What is the use of break and continue in Python?

In Python, break and continue statements can alter the flow of a normal loop. Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.

The break and continue statements are used in these cases.


Break Statement

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You’ll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

 

Syntax of break

Let’s look at an example that uses the break statement in a for loop

In this small program, the variable number is initialized at 0. Then a for statement constructs the loop as long as the variable number is less than 10.

Within the for loop, there is an if  statement that presents the condition that if the variable number is equivalent to the integer 5, then the loop will break.

Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

To know when we are out of the loop, we have included a final print() statement outside of the for loop.

When we run this code, our output will be the following:

 

 

 

[Total: 1    Average: 5/5]
admin
Leave a Reply

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages