Page 152 - Information_Practice_Fliipbook_Class11
P. 152
6.4.3 for Statement vs while Statement
We have already learnt that each of the for and while statements is used for looping. We have already used a
for statement to develop a program that finds the factorial of a number. Now we ask the question: can we compute
the factorial of a number using a while statement? Of course, we can, as illustrated in Program 6.7. A more
serious question to ask is whether we should write a program to compute the factorial of a number using a while
statement. The answer to this question is a resounding "NO." When all we need to do is count up or down, a certain
number of times, a for statement should be the natural choice because that is how we think. For example, while
moderating the results of an examination, a teacher might tell an official: Increase each student's marks by two. In
contrast, imagine the teacher telling the official: while there are students in the class, increase a student's marks by
two. Repeat the process of checking and updating the student's marks until there are no more students left. How
incomprehensible is the second version? The same thing applies to computer programs. As the programs developed
by a programmer need to be maintained. To make the programs readable, we need to be judicious in our choice of
the control structures (or in fact, any syntactic structure), as indiscriminate use of the language's syntax makes the
programs unreadable.
Program 6.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)
6.4.4 More Examples of while Statement
In Table 6.3, we give some more examples of the while loop.
Table 6.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)
138 Touchpad Informatics Practices-XI

