Advertisement



< Prev
Next >



Python Break Statement





Like most of the computer programming languages, Python also provides us a way to exit an executing loop through its break statement i.e. when the break statement is encountered within an executing looping construct like for, while of a program, it stops executing the remaining statements in the loop and takes the control out of it to execute the first statement right after the loop.




Important points about the break statement








Why there is no colon : after the break statement?







Python - break statement(with an if condition) example


#Python - break statement example


count = [1, 2, 3, 4,5]
for x in count:
        if x==3:
                print("Oops it is 3, time to exit!")
                break
        print("x = ", x)
print("Out of the loop")


Output


x =  1
x =  2
Oops it is 3, time to exit!
Out of the loop

As you can see in the program, the break statement is associated with an if condition i.e. when i is equal to 3, the break statement breaks the execution of the loop and it takes the control out of it, to execute the first statement outside the loop.


Advertisement




Python - break statement(without an if condition)


#Python - break statement example


numbers = [1, 2, 3, 4, 5]
for x in numbers:
        print("Hello")
        break
        print("x = ", x)
print("Out of the loop")


Output


Hello
Out of the loop

As you can see in this program, the break statement is not associated with any if condition within a loop, hence this break statement breaks the execution of the loop in the first run of the loop and it takes the control out of it, to execute the first statement outside the loop.



Please share this article -





< Prev
Next >
< Python for loop
Python arithmetic operators >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement