Page 210 - Computer Science Class 11 Without Functions
P. 210
Fig 9.1: Sample execution of program 9.2
To sum up the above discussion of the for statement used in program 9.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 9.2):
For each item in
sequence
Last item True
reached?
False
Statements
Exit for loop
Fig 9.2: for loop
9.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
9.3.2 Factorial of a Number
Given a non-negative integer n, we wish to compute its factorial (n!). So, we write a program to compute the
factorial (n!) of a number num (>=0). The program accepts an integer and outputs its factorial.
208 Touchpad Computer Science-XI

