Page 147 - Information_Practice_Fliipbook_Class11
P. 147
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Let us now see some examples of the use of the for statement that includes an else part.
Example:
>>> for i in range(1,4):
... print('i=', i)
... print('i*i=', i*i)
... else:
... print('End of for loop\'s body')
... 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:
>>> for i in range(4,1):
... print('i=', i)
... print('i*i=', i*i)
... else:
... print('End of for loop\'s body')
... 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')
Looping in Python 133

