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

How To

How to Use the Continue Statement in Python

Contributor
By eHow Contributing Writer
(4 Ratings)

Control flow is a fundamental concept in programming. Web programmers often create loops and test conditions that they wish to step through. Using Python's continue statement, you can implement a way to skip through segments of a for or while loop. The continue statement is used to skip through a block in the current loop.

Difficulty: Easy
Instructions

    Use the Continue Statement in a Python For Loop

  1. Step 1

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

  2. Step 2

    Determine which conditions you wish to test for to see if you want to skip through the loop.

  3. Step 3

    Use an if statement inside the for loop to skip through the loop early. You may use the continue statement inside the nested if/else statement: for k in range(5,10):
       if k > 7:
         print 'skipping this iteration!'
         continue
       print k
    This sample loop logic will print: 5
    6
    skipping the iteration
    skipping the iteration
    skipping the iteration Note that the final print statement is not inside the if block.

  4. Use the Continue Statement in a While Loop

  5. Step 1

    Create a while loop where you may wish to skip through steps: while True:

  6. Step 2

    Determine which conditions you wish to test for to see if you want to skip through the loop.

  7. Step 3

    Use an if statement inside the for while to skip through the loop early. You may use the continue statement inside the nested if/else statement:
    while True:
       my_input = raw_input('Enter a string less than ten characters : ')
         if my_input == 'quit':
         break
       if len(my_input) > 10:
         continue
       print 'You entered something less than 10 characters'

    This loop will continue forever unless the user types "quit", thereby forcing a break statement. If the input that the user enters is greater than 10 characters, it will go back to the top of the while loop, prompting the user for more input. Otherwise, this program will display the string 'You entered something less than ten characters.'

Tips & Warnings
  • You may not use the continue statement inside of Python's "finally" clause.
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.

Demand Media
eHow_eHow Technology and Electronics