Python break Keyword
The Python break is used to control the execution of the loop. It is used to bring the program control out of the loop and executes remaining statements. It is a case-sensitive keyword. If we use this keyword other than, loops it will results in SyntaxError.
The break keyword, incase of nested-loops, it will break the inner-loop first and the control will come to outer loop.In other words, It is used to abort the current execution of the program and control goes to the next line after the loop.
When there are more conditions, but we need to break the loop at particular condition we use break keyword.
Syntax
Following is the syntax of the Python break keyword −
break
Example
Following is an basic example of the Python break keyword −
x = [1, 2, 3, 4, 5]
for i in x:
print(i)
if i == 3:
break
Output
Following is the output of the above code −
1 2 3
Using 'break' Keyword Outside the Loop
The break keyword is used only inside the loop. If we use it outside the loop, it will result an SyntaxError.
Example
Here, we have used the break keyword inside the if block which resulted in error −
var1 = 45
if var1>0:
print("Yes")
break
Output
Following is the output of the above code −
File "/home/cg/root/75154/main.py", line 4
break
^^^^^
SyntaxError: 'break' outside loop
Using 'break' Keyword in while loop
The while loop is an indefinite iterative loop, which means the number of times the loop is executed is not known in advance. To make the indefinite loop to finite loop we use break keyword inside the loop.
Example
Here, we have defined a while keyword and used a break keyword inside it −
while True:
print("Hello Welcome To Tutorialspoint")
break
Output
Following is the output of the above code −
Hello Welcome To Tutorialspoint
Using 'break' keyword in Nested-loop
If there is more than one loop inside a loop, it is known as a nested loop. We can use break keyword inside the nested loops, the execution of the inner-loop breaks first and the outer-loop continues to executes based on its condition.
Example
Following is an example of the break keyword in nested-loop −
for i in range(1,3):
for j in range(0,4):
print("value of inner loop", j)
break
print("value of outer loop", i)
break
Output
Following is the output of the above code −
value of inner loop 0 value of outer loop 1
python_keywords.htm