Interview Questions, Answers and Tutorials

Illustration of a common problem where continue statement is applicable

Illustration of a common problem where continue statement is applicable

In the exciting world of programming, there are various tools that help us solve problems efficiently. One such tool in Python is the “continue” statement. In this course, we will delve into understanding what this statement does and where it can be applied.

What is the “continue” Statement? Imagine you’re on a journey, and suddenly you encounter a roadblock. Instead of giving up, you find a way to bypass it and keep moving forward. That’s exactly what the “continue” statement does in Python. It helps us skip over certain parts of a loop and continue with the next iteration.

Illustrating the Common Problem: Let’s take a simple example to understand where the “continue” statement can be helpful. Suppose we want to print all the numbers from 1 to 10, but we want to skip printing the number 5.

for i in range(1, 11):
    if i == 5:
        continue
    print(i)

Explanation: In this code, we use a loop to iterate through numbers from 1 to 10. Inside the loop, we check if the current number is 5. If it is, we use the “continue” statement, which tells Python to skip the rest of the code inside the loop for this iteration and move on to the next number. So, when the number is 5, it won’t print anything and will move on to the next iteration.

Practice Questions:

  1. Write a Python program to print all even numbers between 1 and 20, skipping the number 10.
  2. Create a Python program that prints the first 10 multiples of 3, but skips printing the number 9.

Solutions:

for i in range(1, 21):
    if i == 10:
        continue
    if i % 2 == 0:
        print(i)
for i in range(1, 31):
    if i == 9:
        continue
    if i % 3 == 0:
        print(i)
    ```
**Explanation of Solutions:**

1. In the first solution, we loop through numbers from 1 to 20. Inside the loop, we first check if the number is 10. If it is, we skip to the next iteration using the "continue" statement. Then, we check if the number is even (divisible by 2) and print it if it is.

2. In the second solution, we loop through numbers from 1 to 30. Inside the loop, we skip the number 9 using the "continue" statement. Then, we check if the number is a multiple of 3 and print it if it is.

**Conclusion:**
The "continue" statement is a powerful tool in Python that allows us to skip over certain parts of a loop. By understanding how and where to use it, we can write more efficient and readable code. Keep practicing and exploring, and you'll soon master this concept!

```