Continue
Introduction:
- The
continuestatement in Python is used to skip further instructions in the loop for the current iteration and continue with the next iteration of the loop.
Syntax:
python
continue
- Just the
continuekeyword on a line by itself.
Examples:
- Continue Statement with While Loop:
This example uses a while loop to print numbers from 1 to 10. The loop skips the numbers 4 and 7.
pythoni = 1 while i <= 10: if i == 4 or i == 7: i += 1 continue print(i) i += 1Output:
1 2 3 5 6 8 9 10
- Continue Statement with For Loop and Range:
This example continues the execution of the for loop when the element is divisible by 3.
pythonfor x in range(1, 11): if x % 3 == 0: continue print(x)Output:
1 2 4 5 7 8 10
Exercises:
- Use Continue in While Loop:
Write a while loop to print numbers from 1 to 10. Skip the numbers 5 and 9.
pythoni = 1 while i <= 10: if i == 5 or i == 9: i += 1 continue print(i) i += 1
- Use Continue in For Loop with Range:
Write a for loop to print numbers from 1 to 15. Skip the numbers that are multiples of 4.
pythonfor x in range(1, 16): if x % 4 == 0: continue print(x)
Summary:
- In this tutorial, we learned how to use the
continuestatement to skip the execution of further statements during an iteration and continue with the next iterations or elements in the collection. Practice using thecontinuestatement in different looping scenarios to understand its functionality and use it effectively in your Python programs!