Skip to main content
Engineering LibreTexts

5.5: Finishing iterations with continue

[ "article:topic", "authorname:severancec", "python (language)", "jupyter:python", "license:ccbyncsa" ]
  • Page ID
    3074
  • Sometimes you are in an iteration of a loop and want to finish the current iteration and immediately jump to the next iteration. In that case you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration.

    Here is an example of a loop that copies its input until the user types "done", but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).

    Code \(\PageIndex{1}\) (Python):

    while True:
        line = input('> ')
        if line[0] == '#':
            continue
        if line == 'done':
            break
        print(line)
    print('Done!')
    
    # Code: http://www.py4e.com/code3/copytildone2.py
    

    Here is a sample run of this new program with continue added.

    > hello there
    hello there
    > # don't print this
    > print this!
    print this!
    > done
    Done!

    All the lines are printed except the one that starts with the hash sign because when the continue is executed, it ends the current iteration and jumps back to the while statement to start the next iteration, thus skipping the print statement.