While Loops In Python

What Is A While Loop?

A while loop is a loop which repeats code statements while meeting a condition. The while loop is an example of a condition controlled loop.

Reference: Starting Out With Python – Second Edition By Tony Gaddis

 


While Loop Format

The format for the while loop in Python is quite simple. Using it though can be tricky as shown in the examples below.

 


Examples

Here are a few examples of using the while loop in Python.

 

Example One

In this first example, the numbers from 1 to 8 are printed in Python. Instead of doing print(1) all the way to print(8), a while loop is used. The counter i is initialized at 1 and is counted up by 1 inside the while loop. The printing of the numbers stop when the condition of i less than or equal to 8 is not satisfied.

 

 

Example Two

This second example features adding numbers from 1 to 100. With math notation we have:

    \[\sum_{i = 1}^{100} i = 1 + 2 + 3 + ... + 98 + 99 + 100\]

In the while loop below, it will be shown that the sum of the integers from 1 to 100 totals up to 5050.

 

 

Example Three

The third example generalizes the second example and allows the user to find the sum of whole positive numbers from 1 to n. This sum appears as:

    \[\sum_{i = 1}^{n} i = 1 + 2 + 3 + ... + (n - 1) + n\]

 

 

 

 

Leave a Reply