python break out of function

python break out of function – Updated 2021

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.

you may also read

Difference Between Java And Python 

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.

 

Also Read 

 

Syntax of break

break

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

number = 0

for number in range(10):
    if number == 5:
        break    # break here

    print('Number is ' + str(number))

print('Out of 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:

 

Output
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Out of loop

You may also like:

  1. medical biller interview questions
  2. slider tab
  3. mobile screen resolution list
  4. html interview questions
  5. Most Common Screen Resolutions In 2020
  6. Accurate Reviews