Page 213 - Computer Science Class 11 Without Functions
P. 213
4 10
5 10
Note that the range() function returns an immutable sequence of values and that the control variable i takes values
from this sequence. So, changing the value of the control variable in the body of the for statement does not change
the flow of execution of the for statement.
9.3.4 More Examples of for Statement
In Table 9.2, we give some more examples of the use of the for statement:
Table 9.2: Statements using for loop
Statements Output Explanation
for ch in 'ABCD': A The control variable ch takes each value in
print(ch) B the sequence of characters: 'A', 'B',
'C', 'D'
C
D
numbers = [9, 0, -4, 23, 17, 56] 0 The control variable n takes values in the
for n in numbers: -4 list numbers, one by one. For each value
of the control variable, n, from the list
if n%2 == 0: 56
numbers, print statement is executed if
print(n) Job Done
n%2 == 0. The statement print('Job
print('Job Done') Done') is not part of the body of the loop,
so it is executed after the loop terminates.
for x in range(30, 50, 5): 30 The control variable, x, takes values in the
print(x) 35 range of 30 to 50 (excluding 50) in steps of
5.
40
45
for p in range(4): 0 1 2 3 The control variable p takes values in the
print(p, end=' ') sequence 0, 1, 2, 3. The default start value is 0.
for p in range(100, 90, -2): 100 98 96 94 92 As the body of the for loop is executed,
print(p, end=' ') BYE the numbers in the range of 100 to 91 (in
steps of -2) are printed. The else part of
else:
the for loop is executed after all iterations
print("BYE")
of the loop have been executed.
for c in 'ROSE': Good Code For each value of the control variable c
if c == 'O': O in the string 'ROSE', the if-else
statement is executed.
print(c) Good Code
else: Good Code
print('Good Code')
for c in 'ROSE': O For each value of the control variable c in
if c == 'O': Good Code the string 'ROSE' the if statement is
executed. The else clause is part of the
print(c)
for statement, and it is executed after all
else:
iterations of the for statement have been
print('Good Code')
completed.
Looping in Python 211

