While Loop in Python
The general format of the while statement is:
1while (condition) :
2 statement
3}
4
Note that a while loop may never execute the statement. The statement is executed repeatedly until condition becomes false.
Unlike for
loop which iterates over a list, for using while
loop you need to have an indicator variable i
and change its value within each iteration. Otherwise you will have an infinite loop.
Example: While Loop
The following example shows how to calculate factorial of 10 using the while loop.
1# Calculate 10! using a while loop
2i = 10
3f = 1
4while ( i > 1 ) :
5 f = i*f
6 i = i-1
7 print(i, f)
8
We start with an iterator i
with a value of 10. Then each time the while loop iterates, we reduce the value of i
by 1. Finally, once i
becomes equal to 1, the while loop
ends. The results are shown below:
19 10
28 90
37 720
46 5040
55 30240
64 151200
73 604800
82 1814400
91 3628800
10
In the above example we used while
loop to calculate the factorial of a number. However, Python's math package also has a function that we can use to calculate the factorial. We will learn more math and statistical functions as we go along.
1import math
2math.factorial(n)
3
The above code will output the factorial of 10, i.e., 3628800.