Page 142 - TP_Prime_V2.2_Class8
P. 142

Types of Iterative Statements


                  Python provides two types of iterative statements for and while.


                   The for Loop

                  The for loop executes a simple or compound statement for a fixed number of times, i.e
           Prime (Ver. 2.2)-VIII  looping a set of instructions for a specified number of times. For loop first initialises the


                  counter variable once, then it checks the range if within range, it executes the statement
                  within for loop and then increments or decrements the counter variable as specified by

                  step_size. The syntax of the for statement is given below:


                                     Syntax

                                     for <counter variable> in range(start, stop, step_size):
          140                        statements


                  The 'in' keyword is known as membership operator that is used to check whether the value

                  exists in a sequence or not. If the value is present in the sequence, the result is True,
                  else False. Python also provide another membership operator named 'not in'. The not in

                  operator is the opposite of the 'in' operator that checks if the value does not exist in the
                  sequence. If the value is not present in the sequence, the result is True else False.

                  The range( ) function is an in-built function in Python. This function generates a sequence

                  of numbers. A sequence is a succession of values bound together by a single name. The
                  range( ) function is generally used in the for loop to iterate over the sequence of numbers.

                  The general syntax for using the range( ) function is given below:

                  •   range(start, stop, step_size): The start specifies the starting point for generating
                     numbers. By default, it starts from 0. The stop specifies the position up to which the

                     numbers are to be generated (last number is not included). The step_size specifies the
                     increment or decrement. By default, the value of the step_size = 1 and numbers are

                     generated with an increment of 1. However, we can generate numbers by specifying the
                     value of step_size according to our requirement.


                  •   range(start, stop): It generates a set of whole numbers starting from ‘start’ to ‘stop–1’.
                     Example: range(3, 9) is equivalent to [3, 4, 5, 6, 7, 8].

                  •   range(stop):  Generates  a  set  of  whole  numbers  starting  from  0  to  (stop–1).

                     Example: range(6) is equivalent to [0, 1, 2, 3, 4, 5].
   137   138   139   140   141   142   143   144   145   146   147