Page 302 - Computer Science V2.0 Class 11
P. 302

>>> Enter marks: 70
               >>> Enter marks: 55
               >>> Enter marks: 75
               >>> Enter marks: 85
               >>> Enter marks: 45
                    average marks: 65.0
              To sum up the above discussion of the for statement used in program 11.2, we give below its syntax:

              for control_variable in sequence:
                  body of for loop
              In the above syntax description,
                for is the keyword.

                in is a keyword (membership operator)
                sequence may be a list, string, tuple or dictionary.
                control variable is a variable that takes the values in the sequence one by one.
                 body of the loop may constitute a single statement or several statements, that will be executed for each value of the
                control variable in the sequence. Statements in the body of the loop are indented at the level of indentation next
                to the level at which the header:

                                         for control_variable in sequence / values in range:
                appears. The first statement that appears at the same level as the header marks the end of the body of the for
                statement. However, a for statement may also be the last statement of a function or a Python script. In such a case,
                the end of the function or the Python script marks the end of the for statement.
              We can also describe the above syntax of the for  statement in the form of a flowchart (see Fig 11.1):

                                                            For each item in
                                                               sequence

                                                       Last item    True
                                                       reached?



                                                            False

                                                      Statements           Exit for loop



                                                           Fig 11.1: for loop

              11.3.1 Using String Sequences in a for Statement

              Suppose we wish to find the number of vowels in a string. For this purpose, let us write a function that accepts as input
              a string and returns the number of vowels in it.

                01 def vowelCount(s):
                02     vowels = 'AEIOUaeiou'
                03     count = 0
                04     for ch in s:
                05         if ch in vowels:
                06             count += 1
                07     return count
                08 s=input('Enter the Strings:')
                09 print(vowelCount(s))



               288   Touchpad Computer Science (Ver. 2.0)-XI
   297   298   299   300   301   302   303   304   305   306   307