Page 305 - Computer Science V2.0 Class 11
P. 305

Example:
                   01 for i in range(1,4):
                   02     print('i=', i)
                   03     print('i*i=', i*i)
                   04 else:
                   05     print('End of forloop\'s body')
                   06     print('Else part may also include several statements')
                 Sample Output:

                      i=1
                      i*i = 1
                      i=2
                      i*i=4
                      i=3
                      i*i=9
                      End of forloop's body
                      Else part may also include several statements
                 Note that the statements in the else-block are executed after all iterations of the loop.

                 Example:
                   01 for i in range(4,1):
                   02     print('i=', i)
                   03     print('i*i=', i*i)
                   04 else:
                   05     print('End of forloop\'s body')
                   06     print('Else part may also include several statements')

                 Sample Output:
                      End of forloop's body
                      Else part may also include several statements
                 Note that as range(4,1) yields an empty sequence, beginning with 4, we cannot count up to 1. So, no iterations of the
                 loop's body are executed. However, the statements in the else-block are still executed.



                         What will be the output produced on the execution of the following program segment:

                         for i in range(-4):
                             print('i=', i)
                             print('i*i=', i*i)
                         else:
                             print('Hello')


                 Example:

                   01 for i in range(6):
                   02     print(i, end=' ')
                   03     i = 10
                   04     print(i)

                 Sample Output:
                      0  10
                      1  10
                      2  10
                      3  10
                      4  10
                      5  10
                                                                                                   Looping in Python  291
   300   301   302   303   304   305   306   307   308   309   310