Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 84 - 2612_Digimind
P. 84

    JUMP STATEMENTS

                      These statements are used to jump out of the loop iterations even if the condition has not become
                      false. They alter the flow of control unconditionally. The jump statements defined in Python are
                      break and continue.

                      BREAK STATEMENT
                      The break statement is used for exiting the program control out of the loop. The break statement
                      stops the execution of the loop and program flow continues to the statement after the loop. It is
                      mostly used when we need to exit a loop prematurely before the loop condition becomes false.
                      Program 5: To demonstrate the use of the break statement in a loop

                          Program5.py

                       File  Edit  Format    Run   Options   Window    Help

                        #Program to show the use of the break statement in the for loop

                        for number in range(0, 12):
                            if(number == 7):
                                break
                            print('Number is:', number)
                        print('Out of loop')

                      On running the above program, we get the following output:
                          Output

                       Number is: 0
                       Number is: 1
                       Number is: 2
                       Number is: 3
                       Number is: 4
                       Number is: 5
                       Number is: 6
                       Out of loop

                      The for loop will print the numbers from 0 to 6 because as soon as the number reaches 7, the
                      break statement is executed, stopping the loop.

                                  What will happen if the increment statement is missing in a while loop?

                      CONTINUE STATEMENT

                      The continue statement causes the program to skip the rest of the statement of the current block
                      and move to the next iteration of the loop. It immediately transfers control to the evaluation of the
                      test expression of the loop for the next iteration of the loop.

                       82   Premium Edition-VIII

| 79 80 81 82 83 84 85 86 87 88 89 |