Page 51 - 2501_KVS_C-8
P. 51

Q7.  Write a program in python to accept a number from the user and COUNT and
                         display the number of EVEN elements up to it. E.g. if the user enters N=5, then
                         output should be: 2 as there are 2 even nos.(2 & 4) up to it.
                  Ans.             N=int(input("Enter a number:"))

                                   count=0
                                   for i in range(1,N+1):
                                         if i%2==0:
                                              count = count+1

                                   print("Total No. of EVEN numbers upto ",N," are : ",count)

                 Let us revise what we have learnt:
                 Ø   The ‘For’ loop is used in Python to repeat instructions for a specific number of times,
                     based on a defined range using the range() function.

                 Ø   The ‘For’ loop executes a block of code for each value in the specified range, with the
                     loop variable updating automatically in each iteration.
                 Ø   Practice problems provide opportunities to apply the ‘for’ loop, such as printing number

                     series, calculating squares, and counting even numbers up to a given limit.


                                                           Exercise



                          Something to know

                   A.    Answer the following questions:

                         1.   What is the meaning of a loop?
                               ________________________________________________________
                         2.   Why is a loop used in programming?
                               ________________________________________________________

                         3.   Which loops are used in Python?
                               ________________________________________________________

                   B.    Predict/Select the correct OUTPUT for each question.
                         1.   for I in range(1, 5):
                              print(I)

                                A.   1                                    C.   0
                                     2                                         1
                                     3                                         2
                                     4                                         3
                                     5                                         4
                                B.   1                                    D.   None
                                     2
                                     3
                                     4


                                                                                       Python                       49
   46   47   48   49   50   51   52   53   54   55   56