Page 136 - Touchpad_Plus_V3.2_Class 8
P. 136

10                               Loops in Python

















                             Your Aim

                             to learn about:
                                    The for Statement              The while Statement         The Infinite Loop
                                     The Jump Statements             Some More Programs



                  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].


               134      Plus (Ver. 3.2)-VIII
   131   132   133   134   135   136   137   138   139   140   141