eHow launches Android app: Get the best of eHow on the go.

How To

How to Use the Break Statement in Python

Contributor
By eHow Contributing Writer
(3 Ratings)

Control flow is a fundamental concept in programming. Programmers often create loops and test conditions which need to be escaped from early. Using Python's break statement, you can implement a way to terminate out of for and while loops.

Difficulty: Easy
Instructions

    Use the Break in a For loop

  1. Step 1

    Create a for loop which you may wish to break out of early:for k in range(5,10):

  2. Step 2

    Determine the conditions that need to be met to leave the loop early.

  3. 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.

  4. 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.

  5. Use the Break in a While Loop

  6. Step 1

    Create a while loop that you may wish to break out of early: while i < 15:

  7. Step 2

    Determine the conditions that need to be met to leave the loop early.

  8. 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

Tips & Warnings
  • If you are using a break statement within a try / except / finally statement inside a loop, the finally clause will be evaluated if the break is caught.
  • Guido Van Rossum's Python tutorial is a great place to start learning the basics of Python, as well as generally learning how to program (see Resources below).
  • You may only use the break statement in Python inside a while or for loop.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

Demand Media
eHow_eHow Technology and Electronics