Quick Reach
The break statement of python
The break statement is used to exit the for loop or while loop in Python. It will terminate the current loop and execution will be moved to next statement outside of the loop.
Python break statement scope is for the current loop only – so if you are using an inner loop (a loop inside a loop) then it will omit/exit the inner loop only.
Example of using break in for loop
Following example uses the break Python statement inside a for loop.
A sequence of four characters is created which is displayed by using a for loop. However, as the loop reaches ‘c’ it will encounter the break statement:
1
2
3
4
5
6
7
8
9
|
i = [‘a’,‘b’,‘c’,‘d’]
for j in i:
if j == ‘c’:
break
print (j)
|
The output will be
a
b
You can see, the loop only printed the value ‘a‘ and ‘b‘. As the loop reached to the value of ‘c’, the condition in the if statement was checked again, that was true this time. Inside the if block, we placed the break statement that immediately exit the for loop. That was the reason why ‘c’ was not displayed in above example.
The break statement in While loop example
The following example uses the break statement in a While loop.
As the variable i reaches the value of 3, it will encounter the Python break statement. See the example by clicking the link below:
1
2
3
4
5
6
7
8
9
10
11
|
i = 1
while i < 5:
print (‘Current value :’, i)
i = i +1
if i == 3:
break
|
Output will be
Current value: 1
Current value: 2
Also see – Python For loop | Python While Loop | Python Continue
Leave A Comment?