Loop Control Statements


 Loop control statements

           Loop control statements change execution from it's normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. 

  Python supports the following control statements.

1. Break statement

      The break is a keyword in python which is used to bring the program control out of the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. In other words, we can say that break is used to abort the current execution of the program and the control goes to the next line after the loop.

           The break is commonly used in the cases where we need to break the loop for a given condition.

Syntax

# loop statements
  
          break

Example 1 :

fruits=["apple","banana","grapes"]

for x in fruits:

        print(x)

        if x=="banana":

                   break

Output

apple

banana

Example 2 :

str="python"

for i in str:

       if i=="o":

                 break

       print(i)

Output

p

y

t

h


           

2. Continue Statement

     When the continue statement is encountered, the control transfer to the beginning of the loop. 

The continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the loop and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular condition.

The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and the loop condition is evaluated again. If the condition is true, then the next iteration takes place.

Syntax

# loop  statements

            continue

# the code to be skipped

Flow Chart


Example 

Fruits=["apple","banana","grapes"]

for x in fruits:

            if x=="banana":

                        continue

            print(x)

Output

apple

grapes

3. Pass statement

              The pass statement is a null operation since nothing happens when it is executed. It is used in the cases where a statement is syntactically needed but we don't want to use any executable statement at its place.

We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes.


Example

# an empty loop

for letter in python:

          pass

print("last latter;", letter)



           

No comments:

Post a Comment