How to Use the Break Statement in Python
Instructions
Use the Break in a For loop
1Create a for loop which you may wish to break out of early:for k in range(5,10):
2
Determine the conditions that need to be met to leave the loop early.
3
Use an if/else statement inside the for loop to leave the loop early. You may use the break statement inside the nested if/else statement: for k in range(5,10):
??if k == 7:
????print 'breaking out of the loop!'
????break
??else:
????print kThis sample loop logic will print:??5
??6
??breaking out of loopAnd then terminate.
4
Understand that the control variable in for loops retain its value after the break. In the above example, the value of k will be 7.
Use the Break in a While Loop
1Create a while loop that you may wish to break out of early:
while i < 15:
2
Determine the conditions that need to be met to leave the loop early.
3
Use an if/else statement inside the for loop to leave the loop early. You may use the break statement inside the nested if/else statement:
i=0
while i < 15:
??i = i+1
??print i
??if i == 4:
????print 'breaking out of loop'
????break
??else:
????print i
This will print:
1
2
3
breaking out of loop