Page 162 - Information_Practice_Fliipbook_Class11
P. 162

03     j = 1
          04         print one *
          05     print newline
          06 i = 2
          07     print 6-2=4 spaces
          08     j = 1
          09         print one *
          10     j = 2
          11         print one space
          12     j = 3
          13         print one *
          14     print newline
          15 i = 3
          16     print 6-3=3 spaces
          17     j = 1
          18         print one *
          19     j = 2
          20         print one space
          21     j = 3
          22         print one space
          23     j = 4
          24         print one space
          25     j = 5
          26         print one *
          27     print newline
          28 and so on
        6.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)




          148  Touchpad Informatics Practices-XI
   157   158   159   160   161   162   163   164   165   166   167