您在這裡

Finishing iterations with continue

23 二月, 2015 - 15:05

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

while True:    line = raw_input('> ')    if line[0] == '#' :        continue    if line == 'done':        break    print lineprint 'Done!'

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

> hello therehello there> # don't print this> print this!print this!> doneDone!

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