Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 145 - CodePilot V5.0 C7
P. 145

    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
                          14     message and exit the loop, showing how many even numbers are entered.

                         Program14.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.

                                                                                                                      143
                                                                                               Flow of Control in Python

| 140 141 142 143 144 145 146 147 148 149 150 |