Page 1 - Lesson Note - Iterative Statement
P. 1

Lesson Note
                                         Iterative Statement


               Iterative statement to use when a task has to be repeated.

               Two types of loop statements in Python:
                  i)   for loop – counting loops, the loops that repeat a certain number of times
                 ii)   while loop - conditional loops that repeat until a certain condition is true

               for loop
               Syntax:
                       for <variable> in <sequence>:
                                statements_to_repeat

                        for x in [4, 5, 6, 7]:   for x in range(4, 8):   for x in range(10, 0, -2)
                               print (x)               print (x*x)              print (x*x)
                        Output                  Output                   Output
                        4                       16                       100
                        5                       25                       64
                        6                       36                       36
                        7                       49                       16
                                                                         4
                        for ch in 'CALM'        sum = 0
                               print(ch)        for n in range (1, 11)
                                                      sum = sum + n
                        Output                  print (sum)
                        C
                        A                       OUTPUT
                        L                       55
                        M

               while loop


               Syntax:
               Evaluates the logical test condition, if true executes the while block, continues execution till
               the test condition evaluates to TRUE.

               while <logical expression>:
                         loop-body

                        x=4                                 a=5
                        while x>0:                          while a<=30:
                            print (x, "in loop")                print (a)
                            x = x-1                             a = a+5

                        Output                              Output
                        4 in loop                           5
                        3 in loop                           10
                        2 in loop                           15
                        1 in loop                           20

                                                            25
   1   2   3   4