Subscribe Contact

Home  »  Chapter 4 : Repetition
while Loops

Overview

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.

General Form

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



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




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:

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.



 





© 2023 John Gordon
Cascade Street Publishing, LLC