Page 133 - Computer Genius Class 08
P. 133

l    In while loop, test expression is checked first. The body of the loop is entered only if the test
                   expression evaluates to True.

                 l    After one iteration, the test expression is checked again. This process continues until the test
                   expression evaluates to False.

                 l  In Python, the body of the while loop is determined through indentation.

                 l  Body starts with indentation and the first unindented line marks the end.

                 l  Python interprets any non-zero value as True, ‘None’ and 0 are interpreted as False.

                 Example 7: ‘While’ loop
                   # Program to add natural numbers upto n.
                   # sum = 1+2+3+...........+n
                   n = 10
                   # Initializ e sum and counter
                   sum = 0
                   i = 1
                   while i<= n:
                     sum = sum + 1
                     i = i + 1
                   # print the sum
                   print ("The sum is", sum)
                 Output:

                   The sum is 55

                 Description:
                 In the above program, sum of the numbers from 1 to 10, has been calculated and printed using
                 ‘While’ loop.



                                                                                      Computational Thinking
                        Quest


                      Find the error in the syntax of if statement and write the correct syntax.

                      if (Test Expression)
                          Indented statement block


















                                                                                    Control Flow Statements   131
   128   129   130   131   132   133   134   135   136   137   138