Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 121 - 2611_SmartGPT Pro V(5.0) C-7
P. 121

    THE BREAK STATEMENT
                     The break statement is used to exit a loop before it has completed all its iterations. When Python

                     encounters break, it immediately stops the loop, exits it and move on to the code after the loop.
                     Program 14. To accept 5 even numbers from the user. If an odd number is entered, display a
                     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 continue, it goes back to the beginning of the loop, without running the
                     rest of the code in that iteration.

                     Program 15. To print only odd numbers, skip any even number.
                         Program15.py

                      File  Edit  Format   Run    Options   Window    Help

                      for i in range(1, 11):
                          if i % 2 == 0:
                              continue  # skip even numbers
                          print("Odd number:", i)
                      print("Out of for loop")

                                                                                               Flow of Control in Python  119

| 116 117 118 119 120 121 122 123 124 125 126 |