__What Is A While Loop?__

__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__

__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.

1 2 3 4 5 6 7 |
# While loop statement: while condition: <put code here> <put code here> <put code here> ... |

__Examples__

__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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Example One (Printing Numbers From 1 to 8): i = 1 #Initialize while i <= 8: print(i) i = i + 1 1 2 3 4 5 6 7 8 |

__Example Two__

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

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Example Two (Adding Numbers From 1 to 100): #Initialize i = 1 total = 0 while i <= 100: total += i i += 1 print(total) 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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Example Three - A Function For Adding Numbers From 1 to n. def total_n(n): counter = 1 total = 0 if n >= 1 and type(n) == int: while counter <= n: total += counter counter += 1 return total else: print("Please enter a whole number that is 1 or greater.") sumTotal = total_n(10) print(sumTotal) 55 |