In the world of programming, Python is one of the most widely used high-level programming languages.
In this tutorial, we will learn a neat trick to skip a line in a for loop using Python. This is essential for controlling the flow of iterations in a loop. Python offers a variety of ways to handle this situation using the continue statement.
What does the continue statement do?
A continue statement is used in Python to skip the rest of the codes inside the enclosing loop for the current iteration and move to the next. Essentially, when the interpreter encounters a continue statement, it will skip the remaining statements of the current iteration and start the next iteration.
Step 1: Basics Python For Loop
Before we go ahead with skipping lines, let’s take an example of a basic Python loop.
1 2 3 |
for i in range(10): print(i) |
This code will print numbers from 0 to 9. These will be printed on separate lines because the print() function by default adds a new line at the end of its output.
Step 2: Skipping a Line
Now, let’s say we want to skip a few numbers and only print the odd numbers. We can do this with the help of the continue statement.
1 2 3 4 |
for i in range(10): if i % 2 == 0: continue print(i) |
The above Python script will only print the odd numbers. Here, for each number, it checks if the number is even (i % 2 == 0). If it is even then it will skip the rest of the code in the loop for the current iteration and move to the next iteration.
Step 3: Use of continue statement in Nested Loops
In the case of nested loops, the continue statement resumes the next iteration of the nearest loop in which it is used.
1 2 3 4 5 6 |
for i in range(1,5): for j in range(i): if j == 2: continue print(j, end = '') print() |
This script will print on different lines digits from 0 to 4, however, it will skip digit 2.
01 01 0123
Summary
The continue statement provides an effective way to control your loop’s flow. Remember, the continue statement only works in while and for loops.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#Print only odd numbers for i in range(10): if i % 2 == 0: continue print(i) #Skipping '2' in nested loops for i in range(1,5): for j in range(i): if j == 2: continue print(j, end = '') print() |
Output
1 3 5 7 9 0 01 01 013
Conclusion
We hope you now understand how to use the continue statement to skip a line in a for loop in Python. Remember, the best way to gain expertise in any programming language is by continuous practice and implementation. Therefore, keep practicing!