Page 105 - modular4.0
P. 105

Chapter Profile
                                                                                         Chapter Profile
                  9                                                                  The for Statement

                                                                                       The while Statement
                                                                                          The Infinite Loop

                                                                                          The Jump Statements


                                                                                           Some More Programs
                           Loops in Python














                 Sometimes, you need to repeat a task multiple times 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

                 The for loop is a type of iterative statement that allows the user to repeat a set of statements
                 multiple times until a given condition is falsified. The for loop is commonly used when the number
                 of iterations is known in advance or when iterating over a sequence, such as a list, string, tuple, or
                 a range.

                 The syntax of for loop is as follows:

                 for <counter variable> in range(start, stop, step_size):
                 statements

                 Using the range() Function
                 The  range() function  is an in-built  function  of  Python.  This function  generates a list which  is a
                 sequence type. A sequence is a succession of values bound together by a single name. The range()
                 function is used in the for loop to iterate over the numbers.

                 The general syntax of using the range() function is given below.
                    range(n): Generates a set of whole numbers starting from 0 to (n–1).
                    Example: range(6) is equivalent to [0, 1, 2, 3, 4, 5].








                                                                                                     Loops in Python  103
   100   101   102   103   104   105   106   107   108   109   110