Python – Break
Python – Break:
In this tutorial, we will learn about the Break statement in Python. Break statement is used to terminate the loop program at a point.
Let us understand the below example which do not have “break” statement will go through multiple iterations till the value of i becomes 109.
Example:
>>> for i in range(100,110): ... print('Assigned value of i is ',i) ... for num in range(100,i): ... print(i,num) ...
Below is the output:
Assigned value of iis 100 Assigned value of iis 101 101 100 Assigned value of iis 102 102 100 102 101 Assigned value of iis 103 103 100 103 101 103 102 Assigned value of iis 104 104 100 104 101 104 102 104 103 Assigned value of iis 105 105 100 105 101 105 102 105 103 105 104 Assigned value of iis 106 106 100 106 101 106 102 106 103 106 104 106 105 Assigned value of iis 107 107 100 107 101 107 102 107 103 107 104 107 105 107 106 Assigned value of iis 108 108 100 108 101 108 102 108 103 108 104 108 105 108 106 108 107 Assigned value of iis 109 109 100 109 101 109 102 109 103 109 104 109 105 109 106 109 107 109 108
Now, let us break the loop when the value of i becomes 105. Below is the code and output for clarification.
Example
>>> for i in range(100,110): ... print('Assigned value of i is ',i) ... for num in range(100,i): ... print(i,num) ... if i==105: ... break ...
Below is the Output:
Assigned value of iis 100 Assigned value of iis 101 101 100 Assigned value of iis 102 102 100 102 101 Assigned value of iis 103 103 100 103 101 103 102 Assigned value of iis 104 104 100 104 101 104 102 104 103 Assigned value of iis 105 105 100 105 101 105 102 105 103 105 104
Share: