What does the continue statement do in a Python loop?

What does the continue statement do in a Python loop?

a) Ends the loop
b) Skips the rest of the current iteration and moves to the next iteration
c) Repeats the current iteration
d) Skips the entire loop

Answer:

b) Skips the rest of the current iteration and moves to the next iteration

Explanation:

The continue statement in Python is used within loops to skip the rest of the code inside the current iteration and move directly to the next iteration. It is often used to bypass certain parts of a loop based on a condition.

for i in range(5):
    if i == 2:
        continue  # Skips the rest of the code for i == 2
    print(i)  # Prints 0, 1, 3, 4

In this example, when i equals 2, the continue statement is executed, causing the loop to skip the print() statement for that iteration and move on to the next iteration.

Using continue allows you to fine-tune loop behavior, enabling you to handle specific cases within the loop without affecting the overall loop execution.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top