Skip Iteration with continue
continue is used to terminate the current iteration and proceed to the next one.
When continue is encountered inside a loop, the code following it is not executed, and the loop condition is re-evaluated to continue with the next iteration.
It is often used when you want to skip certain processes under specific conditions.
Example of using continue
# Loop from 1 to 10 for i in range(1, 11): # If the remainder of i divided by 2 is 0, it's an even number if i % 2 == 0: # Skip the iteration when the number is even continue # Print only odd numbers print(i)
1 3 5 7 9
i % 2 == 0 checks if i is divisible by 2.
The % operator is the modulus or remainder operator, so i % 2 returns the remainder of i divided by 2. If i is even, this will be 0.
In Python, 0 is considered False within an if statement, so if i % 2 == 0: will be True for even numbers.
Thus, whenever i is even, the continue statement is triggered, causing the loop to skip the remaining code for that iteration.
This method ensures that the loop prints only the odd numbers between 1 and 10.
Practical Programming Example
continue is particularly useful when you want to execute code only under certain conditions while iterating through elements.
For example, you can use continue if you want to skip certain characters while iterating through the characters of a string.
text = "Banana" # Iterate through each character in the string and skip 'a' for char in text: # When the character is 'a' if char == "a": # Skip the iteration continue # Print the character print(char)
B n n
In this example, all instances of the character 'a' are skipped, and only the remaining characters are printed.
Lessons in this chapter ยท What are Conditional Statements and Loops?
- 1. The Crossroads of Logical Flow, Conditional Statements
- 2. Using Comparison Operators in Conditional Statements
- 3. Conditions within Conditions, Nested Conditionals
- 4. Combining Conditions for More Powerful Decisions
- 5. Filling in Gaps with the pass Keyword
- 6. Fill-in-the-blank quiz
- 7. Using Loops to Execute Code Multiple Times
- 8. Repeating a Specific Number of Times with a for Loop
- 9. Controlling Loops with the while Statement
- 10. Loop within a Loop, Nested Loops
- 11. Using break to Stop Loops
- 12. Skip Iteration with continue
- 13. Multiple-choice quiz
- 14. Coding Quiz - Python Temperature Converter
The continue statement terminates the current iteration and proceeds to the next iteration.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help