Page 227 - Computer Science Class 11 Without Functions
P. 227

9.8 Infinite Loop

            A while loop becomes an infinite loop if the test condition never yields False. For example,

              01 while True:
              02     s = 1
              03 print(s)

            In the above code snippet, the test expression always yields True. But you may ask, why would anybody write a code
            like the one above. Of course, no one would, except by an error. Next, consider the following code snippet. The code
            aims to find the sum of positive numbers entered by a user. The control leaves the loop as soon as it encounters zero
            or a negative number, and the sum of the positive numbers is printed.

              01 sumNums = 0
              02 num = int(input('enter a number: '))
              03 while num>0:
              04     sumNums = sumNums + num
              05     num = int(input('enter a number: '))
              06 print('Sum of all numbers: ', sumNums)

            In the above code, we are required to include the code to input a number twice, whereas it is indeed part of the loop.
            So, the following code that sets the Boolean expression in the while loop as True would be better:
              01 sumNums = 0
              02 while True:
              03     num = int(input('enter a number: '))
              04     if num>0:
              05         sumNums = sumNums + num
              06     else:
              07         break
              08 print('Sum of all numbers: ', sumNums)
            9.9 pass Statement

            A pass statement is ignored by the Python interpreter. It has the following simple syntax:

                        pass
            It is often used as a stub when we want to leave some functionality to be defined in the future. For example, pass
            statement can be used when no action is required on some conditions. For example,

              01 for letter in 'world':
              02     if letter == 'l':
              03         pass
              04     else:
              05         print(letter, end='')
            Sample Output:
                 word

            It is important to remember that only the pass statement is ignored, other statements if any in the block are not
            ignored. For example,
              01 for letter in 'world':
              02     if letter == 'l':
              03         pass
              04         print(letter, end ='')
              05     else:
              06         print(letter, end='')
            Sample Output:
                 world


                                                                                              Looping in Python  225
   222   223   224   225   226   227   228   229   230   231   232