Page 155 - Information_Practice_Fliipbook_Class11
P. 155

08 '''
              09 n = int(input('Enter n: '))
              10 upperLimit = n
              11 for i in range(2, n):
              12     if n%i == 0:
              13         print(n, 'is not a prime number as', n, '=', i, '*', n//i)
              14         #i divides n
              15         break
              16 else:
              17     print(n, 'is a prime number')
            Sample Output:

             >>> Enter n: 5
                 5 is a prime number
             >>> Enter n: 6
                 6 is not a prime number as 6 = 2 * 3
            In program 6.8, for each value of i, the condition n % i == 0 is evaluated. If the condition n % i == 0 holds, the break
            statement gets executed and the control exits the inner for-loop. Because of the abrupt exit from the for-loop on the
            execution of the break statement, the else clause in the inner for-loop does not get executed. However, if for a given
            value of n, n % i == 0 does not hold for any value of i in range(2, n), then the n must be a prime. In this case, the else
            part of the inner for-loop is executed, and a message is displayed that it is a prime number.

            6.5.2 continue Statement

            The continue statement is also a jump statement, just like the break statement. When a continue statement is
            encountered, the remaining statement(s) in the loop is skipped and the control jumps to the beginning of the loop for
            the next iteration. The flowchart in fig 6.5 illustrates the working of continue statement.

            Syntax:
            continue





                                                    False       Test
                                                              condition




                                                                  True


                                                             Enter Loop




                                                              Continue

                                             Exit Loop

                                                Fig 6.5: Working of continue statement
            As the control moves to the next iteration, firstly, the loop variable is updated with the next value in the sequence
            or range. Thereafter, if the updated loop variable is within the range/ sequence or if the test condition is True, the
            execution of the statements in the body of the loop takes place. Consider the examples given below, that explain the
            working of continue statement in for loop and while loop.





                                                                                              Looping in Python  141
   150   151   152   153   154   155   156   157   158   159   160