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

Data Science in Finance: 9-Book Bundle

Data Science in Finance Book Bundle

Master R and Python for financial data science with our comprehensive bundle of 9 ebooks.

What's Included:

  • Getting Started with R
  • R Programming for Data Science
  • Data Visualization with R
  • Financial Time Series Analysis with R
  • Quantitative Trading Strategies with R
  • Derivatives with R
  • Credit Risk Modelling With R
  • Python for Data Science
  • Machine Learning in Finance using Python

Each book includes PDFs, explanations, instructions, data files, and R code for all examples.

Get the Bundle for $39 (Regular $57)
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.

Data Science in Finance: 9-Book Bundle

Data Science in Finance Book Bundle

Master R and Python for financial data science with our comprehensive bundle of 9 ebooks.

What's Included:

  • Getting Started with R
  • R Programming for Data Science
  • Data Visualization with R
  • Financial Time Series Analysis with R
  • Quantitative Trading Strategies with R
  • Derivatives with R
  • Credit Risk Modelling With R
  • Python for Data Science
  • Machine Learning in Finance using Python

Each book comes with PDFs, detailed explanations, step-by-step instructions, data files, and complete downloadable R code for all examples.