Page 212 - Computer Science Class 11 Without Functions
P. 212
Let us now see some examples of the use of the for statement that includes an else part.
Example:
01 for i in range(1,4):
02 print('i=', i)
03 print('i*i=', i*i)
04 else:
05 print('End of forloop\'s body')
06 print('Else part may also include several statements')
Sample Output:
i=1
i*i = 1
i=2
i*i=4
i=3
i*i=9
End of forloop's body
Else part may also include several statements
Note that the statements in the else-block are executed after all iterations of the loop.
Example:
01 for i in range(4,1):
02 print('i=', i)
03 print('i*i=', i*i)
04 else:
05 print('End of forloop\'s body')
06 print('Else part may also include several statements')
Sample Output:
End of forloop's body
Else part may also include several statements
Note that as range(4,1) yields an empty sequence, beginning with 4, we cannot count up to 1. So, no iterations of the
loop's body are executed. However, the statements in the else block are still executed.
C T 02 What will be the output produced on the execution of the following program segment?
for i in range(-4):
print('i=', i)
print('i*i=', i*i)
else:
print('Hello')
Example:
>>> for i in range(6):
... print(i, end=' ')
... i = 10
... print(i)
...
...
0 10
1 10
2 10
3 10
210 Touchpad Computer Science-XI

