Page 145 - Information_Practice_Fliipbook_Class11
P. 145
>>> 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 6.2, we give below its syntax:
01 for control_variable in sequence:
02 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 Python script. In such a case, the end of 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 6.1):
For each item in
sequence
Last item True
reached?
False
Statements
Exit for loop
Fig 6.1: for loop
6.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 program that accepts as input
a string and returns the number of vowels in it.
01 vowels = 'AEIOUaeiou'
02 mystr = input('Enter a String: ')
03 count = 0
04 for char in mystr:
05 if char in vowels:
06 count += 1
07 print('vowel count:',count)
Sample Output:
>>> Enter a String: Madras
vowel count: 2
Looping in Python 131

