Page 134 - TechPluse_C8_Flipbook
P. 134

On running the above program, we get the following output:






















                  Sometimes, you need to repeat a task multiple time or you may need to repeat the task either a
                  certain number of times or until a condition is satisfied. In Python, the statements that are used
                  to repeat a set of instructions are called iterative or looping statements. Looping statements are

                  very useful and necessary for developing applications.
                  Python provides two types of looping statements—for and while. The for statement is used

                  to repeat an instruction or a set of instructions a fixed number of times. Whereas, the while
                  statement is used to repeat a set of instructions until a condition evaluates to true. Let’s discuss
                  these constructs in brief.

                      THE FOR STATEMENT
                                                                                                           for each item
                  The for statement executes a simple or compound statement for a                          in sequence

                  fixed number of times. The syntax of the for statement is given below:
                                                                                                      Last item    True
                  for <variable> in <iterator>:
                                                                                                      reached?
                         Statements
                                                                                                           False

                  Program 9: To calculate the squares of all the numbers present in                  Body of for
                  the given list.
                  [1, 2, 4, 6, 11, 20]
                                                                                                             Exit loop



              132       Premium Edition-VIII
   129   130   131   132   133   134   135   136   137   138   139