Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 118 - 2620_Birla Open Mind C-8
P. 118

    The Break Statement

                  The break statement is used to terminate a loop prematurely. The break is a keyword in Python which
                  is used for bringing the program control out of the loop. The break statement halts the execution of
                  a loop and program flow switches to the statement after the loop. A single break statement will break
                  out of only one loop.

                  The syntax of the break statement is shown below.
                  Syntax:

                  #loop statement
                      break
                  Program 7: To demonstrate the use of the break statement in a loop

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

                             Interdisciplinary Learning

                             #Mathematics

                     Write a program in Python to find whether a number entered by the user is prime or not.

                                                                                                                 #Coding

                      116  Premium Edition-VIII

| 113 114 115 116 117 118 119 120 121 122 123 |