How to Use the Break Statement in Python

104 13

Instructions

Use the Break in a For loop

1

Create 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

1

Create 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

Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.