Page 217 - Computer Science Class 11 Without Functions
P. 217
Program 9.7 To compute factorial of a number using a while statement
01 '''
02 Objective:
03 Accept a non-negative number from the user and display its factorial
04 Input: num
05 Output: factorial of num
06 '''
07 num = int(input('Enter a non-negative integer: '))
08 #ensure n is an integer and n>=0
09 assert num >= 0
10 product = 1
11 count = 2
12 while(count <= num):
13 product = product * count
14 count = count + 1
15 print('Factorial of', num, 'is', product)
9.4.4 More Examples of while Statement
In Table 9.3, we give some more examples of the while loop.
Table 9.3: Examples of while loop
Statements Output Explanation
i = 1 123456 As the value of i becomes 7, the condition
while i <= 6: evaluates to False and the loop terminates.
print(i, end='') The int objects are displayed one after the
i += 1 other without any spaces as end=''.
i = 1 sum: 55 As the value of i becomes 11, the loop
count = 0 terminates and the statement in the else
while i<=10: block is executed.
count=count+i
i =i +1
else:
print('sum:', count)
n = 8 64 36 16 4 As long as the test condition, n>0 is True, the
while n > 0: Done statements in the body of the while loop will
print(n*n, end=' ') be executed. After the loop terminates normally
n = n-2 (without a break statement), the statement
in the else block print("\nDone") gets
else:
executed.
print('\nDone')
In the case of a while loop, the test condition is checked at the entry point of the loop. So, the loop may not be
executed even once, if the test condition is False. Therefore, always remember to initialize the control variable
before the loop begins. If the initial value is not given to the control variable, the while loop will not execute.
Secondly, the control variable has to be updated inside the while loop, otherwise, the loop will never terminate and
become an infinite loop.
Looping in Python 215

