Showing posts with label Python: Continue Statement. Show all posts
Showing posts with label Python: Continue Statement. Show all posts

Python: Continue Statement

 Python continue statement is used to skip the remaining statements of the current loop and go to the next iteration. In Python, loops repeat processes by their own in an efficient way. But there might be chances, when we wish to leave the current loop entirely, skip iteration or dismiss the control controlling the loop.

In the above cases we use loop control statements. The continue statement is one of the loop control statements that allows us to change the loop's control. Continue statement can be used in both Python while and Python for loop as well. 

Continue statement with for loop:

Here is an example of displaying numbers between 1 to 10 except 8

# displaying numbers between 1 to 10
for iteration in range(1, 11):
# hiding of number 8
    if iteration==8:
        continue
# otherwise print the value of iteration
    print(iteration)

Output:

1
2
3
4
5
6
7
9
10

Here we will execute a loop between 1 to 10 . When iteration is on 8, we'll employ continue statement. So when iteration = 8, it will skip this and loop will continue for further numbers.

Continue statement with while loop:

Here is an example of displaying strings unless letter 't' arrives.

# creating a string
string="Python"
# initializing an iterator
iterator=0
        
#starting a while loop
while iterator < len(string):
    # if loop is at the 't', it will stop the execution.
    if string[iterator] == 't':
        continue
    #otherwise it will print the letter
    print(string[iterator])
    iterator+=1


Output:

P
y

In above example, we have taken string 'Python' and we have used while loop to print each letter of the string unless the value of iterator is less than the string's length and letter 't' arrives.

Python continue statement in list comprehension.
Let's see the example for continue statement in list comprehension.


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# using a list comprehension with continue
sq_num = [num**2 for num in numbers if num%2==0]
        
#this will skip odd numbers and only squares the even numbers

print(sq_num)

Output:
[4, 16, 36, 64, 100]

Differences between continue and pass statements:
Definition: The continue statement is utilized to skip the current iteration, go to the next one and return control to the beginning where as pass statement is used when phrase is required on a place syntactically but not to be executed.

Action: Continue statement takes the control back to the start of the loop, whereas nothing happens in case of pass statement.

Python: Functions