Page 49 - 2501_KVS_C-8
P. 49

Now, to execute the above program in Python language, we have to learn the ‘for’ loop. Let
                 us discuss it.
                     ‘for’  loop: A ‘for’ loop is a type of looping statement that is used to execute some

                     commands again and again up to a specific number of times. Its syntax in python is given
                     below:
                          for <loop-variable> in range(<lower-limit>,<upper-limit>):

                                      Statement – 1
                                      Statement – 2

                                      .                            Body of the ‘for’ loop
                                      .

                                      Statement – N

                 Let us discuss the elements of ‘for’ loop in details:
                     ‘for’ is a keyword and used to create a for loop.

                     Loop-variable is the name of the variable which is used to run the loop and whose value
                     will increase automatically by 1.

                     ‘in’ is a reserved keyword used to check the value of loop-variable in the sequence of
                     the values generated by range() function.
                     The range() function is discussed above in the previous article.

                     Statement -1, 2, …., N are the statements/commands which are to be executed in the
                     loop again and again.

                 Now, let us create the program we have discussed above i.e. to print the natural numbers
                 up to 10 using ‘for’ loop:

                                           print("Natural Numbers upto 10 are:")
                                           for COUNT in range(1,11):
                                                 print(COUNT)


                                           OUTPUT:-
                                           Natural Numbers upto 10 are:
                                           1
                                           2
                                           3
                                           4
                                           5
                                           6
                                           7
                                           8
                                           9
                                           10
                 In the above example, we have taken COUNT as the loop-variable and assign it  a value 1 as
                 lower-limit in the range() function. Also, we have assigned the value upper-limit as 11 which
                 is 1 more than 10 up to which we have to print the natural numbers.


                                                                                       Python                       47
   44   45   46   47   48   49   50   51   52   53   54