Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python continue Keyword



The Python continue keyword is a control statement. It is used to skip the current iteration based on the condition and execute remaining iterations in a loop. It is a case-sensitive keyword.

The continue keyword is used only inside the loops. If it used outside the loop it will result an SyntaxError.

Syntax

Following is the basic syntax of the Python continue keyword −

continue

Example

Following is a basic example of Python continue keyword −

for i in range(0,7):
    if i==5:
        continue
    print(i)

Output

Following is the output of the above code −

0
1
2
3
4
6

Using 'continue' Keyword Outside the Loop

If we use the continue keyword apart from the loops, it will result aSyntaxError.

Example

Here, we used the continue keyword inside the if block it result an error −

var1 = 10
if var1 > 5:
    continue

Output

Following is the output of the above code −

File "E:\pgms\Keywords\continue.py", line 18
    continue
    ^^^^^^^^
SyntaxError: 'continue' not properly in loop

Using 'continue' Keyword in while loop

The continue keyword is used inside the while loop, to end the current iteration based on the given condition and executes the remaining iterations.

Example

Here, we have created a string and iterated through while loop and skipped the iteration at s character −

var1 = "Tutorialspoint"
iteration = 0
while iteration < len(var1):
    if var1[iteration] == 's':
        iteration = iteration + 1
        continue
    print(var1[iteration])
    iteration = iteration + 1

Output

Following is the output of the above code −

T
u
t
o
r
i
a
l
p
o
i
n
t

Using 'continue' Keyword in List

The continue keyword can also be used to list iteration, in which some iterations are skipped based on the condition.

Example

Here, we have created a list and printed the square of the even numbers and end the other iterations using continue keyword −

list1 = [1, 2, 3, 4, 5, 6]
for i in list1:
    if i%2!=0:
        continue
    print(i**2)

Output

Following is the output of the above code −

4
16
36
python_keywords.htm
Advertisements