-
Step 1
Create a for loop which you may wish to break out of early:for k in range(5,10):
-
Step 2
Determine the conditions that need to be met to leave the loop early.
-
Step 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. -
Step 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.
-
Step 1
Create a while loop that you may wish to break out of early:
while i < 15: -
Step 2
Determine the conditions that need to be met to leave the loop early.
-
Step 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











