Page 245 - Computer Science Class 11 With Functions
P. 245
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.
10.3.5 More Examples of for Statement
In Table 10.2, we give some more examples of the use of the for statement:
Table 10.2: Statements using for loop
Statements Output Description
for ch in 'ABCD': A The control variable ch takes each
print(ch) B value in the sequence of characters:
C 'A', 'B', 'C', 'D'
D
numbers = [9, 0, -4, 23, 17, 56] 0 The control variable n takes values
for n in numbers: -4 in the list numbers, one by one. For
each value of the control variable,
if n%2 == 0: 56
n, from the list numbers, print
print(n) Job Done
statement is executed if n%2 == 0.
print('Job Done')
The statement print('Job 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
print(x) 35 the 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
print(p, end=' ') in the sequence 0, 1, 2, 3. The default
start value is 0.
for p in range(100, 90, -2): 100 98 96 94 92 BYE As the body of the for loop is executed,
print(p, end=' ') the numbers in the range of 100 to 91
else: (in steps of -2) are printed. The else
part of the for loop is executed after
print("BYE")
all iterations of the loop have been
executed.
for c in 'ROSE': Good Code For each value of the control variable
if c == 'O': O c 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
if c == 'O': Good Code in the string 'ROSE' the if statement
is executed. The else clause is
print(c)
part of the for statement, and it is
else:
executed after all iterations of the for
print('Good Code')
statement have been completed.
Looping in Python 243

