Skip to content

Python break Statement for Loop – While & For

Python break Statement (Keyword) used to break out a for loop or while loop. To a Loops you have to use the Break statement inside the loop body (generally after if condition).

Why you needed to break a loop?

Because if you have some external condition and want to end it. For example, you are searching a name in the student list, once you got the name you need to break the loop.

Python break Statement for Loop While For

Syntax

break

Example of Python break keyword

You can use it Python for and while loops.

1. For-loop

Printing a number within a given rang but on value 3 break the loop.

for i in range(9):
    if i > 3:
        break
    print(i)

Output:

0
1
2
3

2. While loop

Break out of a while loop if “I==6”.

i = 4
while i < 9:
    print(i)
    if i == 6:
        break
    i += 1

Output:

4
5
6

Q: What if we are using a break statement in a nested loop?

Answer: In the nested loops, the break statement stops the execution of the innermost loop and starts executing the next line of code after the block.

Do comment if you have any suggestions and doubts on this tutorial.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python break Statement Programs are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading