While Loop in Python

The general format of the while statement is:

while (condition) :
    statement
}

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.

# Calculate 10! using a while loop
i = 10
f = 1
while ( i > 1 ) :
    f = i*f
    i = i-1
    print(i, f)

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:

9 10
8 90
7 720
6 5040
5 30240
4 151200
3 604800
2 1814400
1 3628800

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.

Related Downloads