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

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.

import math
math.factorial(n)

The above code will output the factorial of 10, i.e., 3628800.

Related Downloads

Membership
Learn the skills required to excel in data science and data analytics covering R, Python, machine learning, and AI.
I WANT TO JOIN
JOIN 30,000 DATA PROFESSIONALS

Free Guides - Getting Started with R and Python

Enter your name and email address below and we will email you the guides for R programming and Python.

Saylient AI Logo

Take the Next Step in Your Data Career

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