A for loop in Python is a control flow statement for traversing items in a collection or sequence such as lists, tuples, and dictionaries.
However, there are situations when you need to exit a loop prematurely, such as when a certain condition is met or an error occurs. In this tutorial, we will learn how to end a for loop in Python using the break and continue statements.
Step 1: Understanding the break statement
The break statement is used to exit a loop before it has completed all iterations. When the break statement is encountered inside the loop, the control flow jumps out of the loop, and the loop terminates.
1 2 3 4 |
for number in range(1, 10): if number == 5: break print(number) |
In the example above, we can observe that the loop is designed to iterate from 1 to 9. However, we have added a condition to break the loop when the variable number
is equal to 5. The output of the code will only be:
1 2 3 4
Step 2: Understanding the continue statement
The continue statement, on the other hand, does not terminate the loop but rather jumps back to the beginning of the loop and continues with the next iteration. Consider the following example:
1 2 3 4 |
for number in range(1, 10): if number == 5: continue print(number) |
In this example, we have added a condition to continue the loop when the variable number
is equal to 5. The output of the code will be:
1 2 3 4 6 7 8 9
Although 5 is still part of the range, the continue statement tells Python to skip the current iteration and move on to the next one.
Step 3: Implementing nested for loops with break and continue
In nested for loops, break and continue statements work in a similar way. They only affect the loop they are in, leaving other loops unaffected. Consider the following example of nested for loops:
1 2 3 4 5 |
for i in range(1, 4): for j in range(1, 4): if j == 2: break print("i:", i, "j:", j) |
This loop is designed to print the values of i and j, but with the break statement, the inner loop terminates when j is equal to 2. The output of the code will be:
i: 1 j: 1 i: 2 j: 1 i: 3 j: 1
Full Code Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
for number in range(1, 10): if number == 5: break print(number) print("\n") for number in range(1, 10): if number == 5: continue print(number) print("\n") for i in range(1, 4): for j in range(1, 4): if j == 2: break print("i:", i, "j:", j) |
Conclusion
In this tutorial, we learned how to end a for loop in Python using the break and continue statements.
The break statement is used to exit and terminate the loop, while the continue statement is used to skip the current iteration and proceed with the next one.
Understanding how to use these statements is essential in writing efficient and effective Python code.