Repetition is so common in programming that most programming languages have standard repetition structures such as while loops and for loops. This is good news because the concept behind these loops is generally the same across languages, so understanding them conceptually in one language transfers to other languages.
The while loop is a condition-controlled repetition structure that repeats one or more statements until a condition is met. The condition is generally a boolean expression which can be a simple condition or compound condition. The while loop is also a pre-test loop, which means it evaluates the condition before anything inside the loop executes. This fact means we often have to prepare variables or conditions before the while statement for the condition evaluation to work as we intend.
The general code form and flowchart representation of the while loops are as follows:
while boolean_expression:
statement_1
statement_2
.
.
statement_n
Code Details:
The boolean_expression can be any logical expression that evaluates to either True or False.
When the boolean_expression evaluates to True, statement_1 thru statement_n repeat until the condition(s) evaluate to False.
Note that the while statement must end with a colon (:).
Note that all statements included in the loop must be indented.
Flowchart Details:
The execution path includes any code before the while statement.
The boolean_expression is represented by the diamond shape.
When the boolean_expression evaluates to True, execution enters the loop and the Statement(s) are executed each time the loop repeats.
Execution remains in the loop until the boolean_expression evaluates to False.
When the boolean_expression evaluates to False execution exits the loop and continues to the next statement after the loop.
Let's take a look at a few examples.
Examples
Example 1
Problem: Print integers from 1 to 10 using a while loop.
Solution:
x = 1
while x < 11:
print(x)
x = x + 1
# See assignment operator note below
Code Details:
Line 1 is not part of the loop. As indicated above, because the while loop is a pre-test loop we often set up variables before the loop starts to support the loop condition(s). In this case, we're creating the variable x and initializing it to 1. We will use x in our loop as a counter.
The while statement on Line 2 sets the condition of x < 11, which means the loop will repeat as long as the value of x is less than 11.
In Line 3 we print the value of x.
And Line 4 adds one (increments) to the value of x. By incrementing x each time through the loop eventually x will equal 11 and the loop condition will evaluate to False and the loop will terminate.
Program Output:
1
2
3
4
5
6
7
8
9
10
Flowchart Details:
Compare the flowchart to the Code Details.
Note that the flowchart presents a visual representation of the code solution and visa versa.
The flowchart includes a Start and End to depict the entire execution path of the code solution. In larger programs, the execution path would be larger and the loop would be only one segment of the larger codebase.
Assignment Operator Note: In the code solution for Example 1 above, I wrote x = x + 1 to increment the value of x. While this works, it is more common to use a more abbreviated form using the Addition Assignment Operator like this:
x += 1
This performs the same operation as x = x + 1 and is more efficient. Python supports numerous Assignment Operators, which you can review on the Operators Reference Materials page (which opens in a separate tab).
Problem 1
How could we change the code in Example 1 to print the numbers from 1 to 10 in reverse order? Like this:
10
9
8
7
6
5
4
3
2
1
There are several ways we could approach this, but here is a straightforward solution:
Python Code
x = 10
while x > 0:
print(x)
x -= 1
Solution Notes:
Study the differences between this code and the original code in Example 1 above.
Notice that our variable is initialized to 10, instead of 1.
The while condition is different as well, now it indicates that the loop will continue while x is greater than zero.
Also notice this time I used another variation of the assignment operator, this time it is the subtraction assignment operator which deducts 1 from the variable (x) each time that line runs.
So, by setting our initial value of x to 10 and deducting 1 from x each iteration of the loop, eventually x becomes zero and the condition fails and we exit the loop.
Problem 2
How could we change the code in Example 1 to print only the odd numbers between 1 and 10? or only the even numbers? Like this:
Odd only:
1
3
5
7
9
Even only:
2
4
5
6
10
As we saw in Question 1 above, to change how a while loop counts is a matter of manipulating the code elements that control the boolean expression. In this question, the changes needed are minor but important to understand.
Here's the code to print only the odd integers between 1 and 10:
Python Code
# Odd integers
x = 1
while x < 11:
print(x)
x = x + 2
Solution Notes:
Study the differences between this code and the original code in Example 1 above.
Notice the only change we needed here is on Line 5 we changed x = x + 1 to x = x + 2.
The change in the increment gives us the odd integers because we initialized x to 1 before the loop.
And the code to print only the even integers between 1 and 10:
# Even integers
x = 2
while x < 11:
print(x)
x = x + 2
Code Details:
Study the differences between this code and the original code in Example 1 above.
Notice the change made here starts with the initilization of our variable. Initializing it as x = 2 on Line 2 sets the while condition to start with 2, then the subsequent increment on Line 5 increments by two, which gives us the even integers that we want.
Example 2
Problem: Prompt the user to enter integers. Accumulate the integers they enter until they indicate they are finished entering integers. Then print a report of how many integers they entered, the sum of all the integers, and the average of their integers.
This problem demonstrates several key uses of while loops, including giving users control over entering data, accumulating data values and producing summaries of that data, and handling numerous variables through a repetition structure.
Solution:
user_int = 0
counter = 0
int_sum = 0
print("-" * 50)
print("Enter a series of integers and")
print("receive a summary report.")
print("-" * 50)
print("When finished, press Enter")
print("at the prompt with no integer.")
print("-" * 50)
user_int = input("Enter your first integer: ")
while user_int != "":
int_sum = int_sum + int(user_int)
counter += 1
user_int = input("Enter your next integer: ")
print("-" * 50)
print("Summary Report")
print("-" * 50)
if counter > 0:
print("You entered " + str(counter) + " integers.")
print("The sum of your integers is " + str(int_sum) + ".")
print("The average of your integers is " + str(int_sum / counter) + ".")
else:
print("You entered no integers.")
print("-" * 50)
This is a more substantial program than we have seen thus far, so take your time and work through the following code details that explain each line of this program.
Code Details:
As indicated in the problem description, we will use several variables in this program.
The variable user_int initialized on Line 1 to 0, will hold each integer value entered by the user.
The variable counter initialized on Line 2 to 0, will be incremented in the while loop each time the user enters another integer so that we know how many they entered in total.
The variable int_sum initialized on Line 3 to 0, is an accumulator, that is, each time the user enters an integer we add their integer to int_sum so that by the end we will have the sum of their integers.
On Lines 4, 7, 10, 16, 18, and 25 we use Python's ability to repeat a character using the * operator to draw a dashed line as separators for our output. This is commonly used to produce well-formatted output.
On Lines 5, 6, 7, and 8 we print instructions for the user.
Line 11 demonstrates the input statement to prompt the user for (in this case) an integer. Notice that the input statement includes the prompt text inside its parentheses. The user_int variable will contain what they type when they press Enter. Also, remember that anything typed by the user at an input prompt will be a string (including numbers) so we will have to cast their entries which we see on Line 13.
Line 12 contains our while loop. Notice the syntax here: while user_int != "":. What does this mean? Again, remember that the user's entry at the input prompt is a string, so we can take advantage of this fact by using, as our boolean expression, user_int != "" which means this while loop will continue until the user presses Enter without entering a value, as indicated in our user instructions on Lines 8 & 9 in the code.
Line 13 is our accumulation line, each time a user enters an integer we cast their entry (stored in the user_int variable) to an integer and add it to the int_sum accumulator variable. In this manner, each iteration of the loop builds a running total of their integers.
On Line 14 we increment our counter variable. Like the sum accumulator, incrementing this counter variable provides us with a running total of the number of integers they have entered.
Line 15 prints a new prompt on the screen asking them for their next integer. Notice that because this is inside the loop (we know this because it is indented), each time the user enters a new integer this prompt will appear again and again until the user presses Enter without typing an integer as instructed above.
The while loop is contained on Lines 12 thru 15. Notice the indentation, it is a requirement of Python for that indentation to be used to indicate what statements are part of the loop.
Line 17 prints a report header line, this is for user-friendliness.
Line 19 is an example of programmatic validation. We will discuss this a lot more later, but this is a good example to introduce the idea of validating user input and data in our programs. The purpose of this particular validation, if counter > 0: ensures that the user has entered at least 1 integer. If they don't then we do not want to perform the calculations because we'll get a runtime error. Any idea why?
The runtime error would occur if no values were entered, that is, the user pressed Entry with no value on the first prompt because computers cannot divide by zero so the average calculation on Line 22 would throw an error. So, to avoid this, we confirm at least 1 value was entered with the if statement.
If values were entered, then Lines 20, 21, and 22 would run and print summary values for the counter, sum, and average.
If no values were entered, the counter would still be zero (it was initialized to 0 on Line 2) therefore the else statement would run the print statement on Line 24.
Infinite Loops
As indicated above, while loops are pre-test loops that depend on a boolean expression condition to determine if the statements inside the loop should run and how many times. What if that boolean expression remains true, that is, there is no change to the boolean expression variables in the loop that causes it to ever turn false? The result is, what we call, an infinite loop. Infinite loops can occur accidentally though an error in coding or logic, or they can be intentional. In either case, if not terminated in some way, an infinite loop would repeat forever.
Consider the following code:
while True:
print("Hello")
If we run this code, what is the result? Since the boolean expression condition of this while loop is simply True, and nothing inside the loop statements will terminate the loop, it will run forever.
Here's another example:
x = 1
while x > 0:
print("Hello")
This is also an infinite loop. Why? Our boolean expression is valid and will run the loop as long as x is greater than zero. The problem is that we initialized x to equal 1, and there is nothing in the loop that changes the value of x, so it remains 1 which is greater than zero, so the boolean expression never turns False. This is a common mistake, where we write a while condition but inadvertently forget to include code inside the loop to finish the loop.
The break Statement
Python includes a break statement that terminates the execution of a loop. This is often called brute force termination because your boolean expression should handle the termination of a loop. However, the break statement is useful in some circumstances. Use of the break statement is often strongly discouraged in production code. Here's an example of its use:
counter = 1
while True:
print(counter)
counter += 1
if counter > 75:
break
print("Done")
This example is similar to our first infinite loop example above. The boolean expression is while True: so this loop will not terminate on its own based on the while condition. However, we've set a counter and increment the counter inside the loop. The if statement inside the loop includes a boolean expression that monitors the value of the counter variable. When that value is greater than 75, we use the break statement and the loop terminates.
This last example simulates what is called a counter-controlled loop, which Python provides and is called the for loop. We will cover the for loop on the next page.