Page 221 - Computer Science Class 11 Without Functions
P. 221
Program 9.9 To accept 5 numbers (except 0) and display their product.
01 #Objective: To accept 5 numbers (except 0) and display their product.
02 P = 1
03 for count in range(1, 6):
04 num=int(input('Enter a number : '))
05 if num == 0:
06 print(' ZERO will not be multiplied')
07 continue
08 P = P * num
09 print('The Product is : ', P)
Sample Output:
>>> Enter a number : 4
>>> Enter a number : -9
>>> Enter a number : 5
>>> Enter a number : 0
ZERO will not be multiplied
>>> Enter a number : -3
The Product is : 540
In program 9.9, if the user enters 0, the continue statement skips the rest of the loop statements and causes the next
iteration of the loop without executing the statement, P = P * num.
9.6 Nested Loops
When a loop appears within another loop, it is called a nested loop. An inner loop is part of the body of the outer
loop. The inner loop is executed win each iteration of the outer loop. Nesting may be continued up to any level. The
following examples will illustrate the use of nested loops.
9.6.1 Understanding Nested Loops
Let us examine the following code snippet:
01 for i in range(1,3):
02 print('In the outer loop, i:', i)
03 for j in range(1,4):
04 print(' In the Inner loop (i,j)', (i,j))
In the above code snippet, there are two loops involving the for statement. We call the first loop the outer loop and
the second loop the inner loop. Accordingly, the first for statement is referred to as the outer for statement, and
the second for statement is referred to as the inner for statement. The control variable i in the outer for loop
takes values in the range(1,3), i.e., 1 and 2. For each value of i, the following two statements form the body of
the for loop. As the second statement in the body is itself a for statement, its body is executed for each value of the
control variable j in range(1,4), i.e., 1, 2, 3. Thus, we get the following output:
In the outer loop, i: 1
In the Inner loop (i,j) (1, 1)
In the Inner loop (i,j) (1, 2)
In the Inner loop (i,j) (1, 3)
In the outer loop, i: 2
In the Inner loop (i,j) (2, 1)
In the Inner loop (i,j) (2, 2)
In the Inner loop (i,j) (2, 3)
Looping in Python 219

