6.4. Finishing iterations with continue
¶
Sometimes, you are in a loop and want to finish the
current iteration and immediately jump to the next. 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).
Here is a sample run of this new program with continue
added:
Try the code block above using the input below as well as your own input.
> 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.
- nothing prints
- Incorrect! Something will print, regardless of what is inputted. Try again.
- 'Done!'
- Entering 'done' will print 'Done!'.
- '#'
- Incorrect! This will not print "#". Try again.
- it will prompt the user for input with '> '
- Incorrect! This would be true if the user entered '#'.
Q-2: What prints if the user’s input is ‘done’?
while True:
line = input('> ')
if line[0] == '#' :
continue
if line == 'done':
break
else:
print(line)
print ('Done!')
Construct a block of code that prints the numbers 1 through 10, but skips the number 8. The loop will start by incrementing n, before doing anything else. Look out for the three extra code pieces and watch your indentation!