Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 92 - 2629_Devagiri_C-8
P. 92

    JUMP STATEMENTS

                      Sometimes,  you  may  want to  stop  a loop  early or skip  certain  steps  inside  a loop.  In  such

                      cases, Python provides jump statements to control the flow of the loop. Python offers two jump
                      statements—break and continue, which are used within loops.

                      THE BREAK STATEMENT
                                                                                        The break statement only exits
                      The break statement is used to exit a loop before it has          the immediate loop in which it
                      completed  all its  iterations.  When Python  encounters          is written; it does not affect any
                      break, it immediately stops the loop, exits it and move on                 outer loops.
                      to the code after the loop.

                       Program  To accept 5 even numbers from the user. If an odd number is entered, display a
                           7      message and exit the loop, showing how many even numbers are entered.

                          Program7.py
                       File  Edit  Format   Run    Options   Window    Help

                       count = 0
                       while count < 5:
                           num = int(input("Enter an even number: "))
                           if num % 2 != 0:
                               print("Odd number entered. Exiting.")
                               break  # stop the loop if number is odd
                           count += 1
                       print("You entered",count,"even numbers.")

                          Output
                       Enter an even number: 2
                       Enter an even number: 6
                       Enter an even number: 8
                       Enter an even number: 5
                       Odd number entered. Exiting.
                       You entered 3 even numbers.

                      THE CONTINUE STATEMENT

                      The continue statement is used to skip the current iteration of
                      the loop and move to the next one. When Python encounters            The continue statement only
                      continue, it goes back to the beginning of the loop, without         skips the immediate iteration
                      running the rest of the code in that iteration.                          in which it is written.

                       90
                            Premium Edition-VIII

| 87 88 89 90 91 92 93 94 95 96 97 |