Python – continue keyword and loops
In this article, we will discuss the syntax and usage of the ‘continue’ keyword. We will also cover the examples of continue keyword in both while loop and for loop.
In python, a ‘continue’ statement inside a loop can make the control jump back to the starting of the loop. If the interpreter encounters a ‘continue’ statement in a loop block, then it skips all the statements or lines after it in the suite and goes back at the beginning of the loop.
Let’s understand by some examples,
While loop with continue statement
Calling the continue keyword inside the loop, will make the control jump to the starting of the while loop again. All the lines after the continue keyword will get skipped for that particular iteration.
x = 0 # Infinite While Loop while x <= 10: x += 1 # If x is bw 4 and 6, then skip printing if 4 <= x <= 6: continue print(x)
1 2 3 7 8 9 10 11
In this while loop, we are printing numbers from 1 to 10. But inside the loop body, we have a check that if x is between 4 to 6, then execute the continue keyword.
So, when the value of x becomes 4, the continue statement gets executed. It forces the control back to the starting of the loop, and the print statement at the end of the loop body gets skipped.
Similarly, the print statement in the loop gets skipped when the value of x is between 4 and 6.
For loop with continue statement
sample_str = 'Sample Text' # Iterate over all the characters in string for elem in sample_str: # If char is not lower case then skip printing if elem.islower() == False: continue print(elem)
a m p l e e x t
In the above example, it is iterating over all the characters in a string and printing them. But only lower case characters are published. All other characters, like upper case characters and whitespaces, get skipped.
To do that, we added an if check inside the for loop, which checks if the character is lower case or not. If no, then calls the continue statement, which makes the control jump to the starting of for loop, and the print statement gets skipped for that iteration.
We can skip certain lines inside the loop body for some iterations using the continue statement. Generally, the ‘continue’ statement is used inside an if block in the loop body.