How does the continue statement affect a for loop in Python?

How does the continue statement affect a for loop in Python?

a) It terminates the loop
b) It restarts the loop
c) It skips the current iteration and proceeds to the next
d) It causes an error

Answer:

c) It skips the current iteration and proceeds to the next

Explanation:

The continue statement in a Python for loop skips the rest of the code inside the loop for the current iteration and proceeds to the next iteration. It is used to bypass specific parts of the loop when certain conditions are met.

for i in range(5):
    if i % 2 == 0:
        continue  # Skips the print statement for even numbers
    print(i)  # Prints only odd numbers: 1, 3

This example demonstrates how the continue statement allows the loop to skip even numbers and only print odd numbers. The continue statement provides a way to skip unnecessary operations and make the loop more efficient.

Leave a Comment

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

Scroll to Top