Page 241 - Computer Science Class 11 With Functions
P. 241
>>> 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 10.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 10.1):
For each item in
sequence
Last item True
reached?
False
Statements Exit for loop
Fig 10.1: for loop
10.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))
Looping in Python 239

