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:
1 2 3 4 |
for i in range(1, 6): if i == 3: continue print(i) |
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.
1 2 3 4 5 6 7 8 9 |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_sum = 0 for num in numbers: if num % 2 != 0: # If the number is odd continue even_sum += num print("Sum of even numbers:", even_sum) |
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:
1 2 3 4 5 6 7 8 9 10 |
counter = 0 total_sum = 0 while counter < 20: counter += 1 if counter % 2 == 0: continue total_sum += counter print("Sum of odd numbers between 1 and 20:", total_sum) |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_sum = 0 for num in numbers: if num % 2 != 0: # If the number is odd continue even_sum += num print("Sum of even numbers:", even_sum) counter = 0 total_sum = 0 while counter < 20: counter += 1 if counter % 2 == 0: continue total_sum += counter print("Sum of odd numbers between 1 and 20:", total_sum) |
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.