How To Restart A Loop In Python

In this tutorial, we will learn how to restart a loop in Python. It’s a useful technique for when you need to break out of the execution of the current iteration and start the next iteration from the beginning.

We will be using the continue statement in Python, which helps us achieve this functionality. Let’s dive into the steps to see how it works.

Step 1: Understanding continue statement

The continue statement is used inside a loop (for or while) to skip the remaining part of the loop’s code block and jump directly to the beginning of the next iteration. Here is a basic example demonstrating its use:

In this example, the continue statement is inside a for loop. When the loop reaches the value of i == 3, it will skip the print(i) statement and directly go to the next iteration.

Step 2: Utilizing continue in a loop

Let’s say you have a list containing integers and you want to find the sum of all the even numbers in that list. You can use the continue statement to achieve this.

Output:

Sum of even numbers: 30

In the code above, when the loop encounters an odd number, the continue statement is triggered, skipping the remaining code block and starting the next iteration.

Step 3: Using continue with a while loop

continue statement also works seamlessly with while loops. Let’s consider an example:

Output:

Sum of odd numbers between 1 and 20: 100

In the above example, we used the continue statement to skip the even numbers and only add odd numbers to the total_sum.

Full Code

Conclusion

The continue statement allows us to easily restart a loop in Python, skipping the remaining part of the code block and moving directly to the next iteration. This enables us to have more control over the execution flow and handle specific cases as needed.