Calculations

Counting and Summing Loop Examples

For example, to count the number of items in a list, we would write the following for loop:

count = 0

for itervar in [3, 41, 12, 9, 74, 15]:
    count = count + 1

print 'Count: ', count

We set the variable count to zero before the loop starts, then we write a for loop to run through the list of numbers. Our iteration variable is named itervar and while we do not use itervar in the loop, it does control the loop and cause the loop body to be executed once for each of the values in the list.

In the body of the loop, we add 1 to the current value of count for each of the values in the list. While the loop is executing, the value of count is the number of values we have seen "so far".

Once the loop completes, the value of count is the total number of items. The total number "falls in our lap" at the end of the loop. We construct the loop so that we have what we want when the loop finishes.

Launch Exercise

Another similar loop that computes the total of a set of numbers is as follows:

total = 0

for itervar in [3, 41, 12, 9, 74, 15]:
    total = total + itervar

print 'Total: ', total

In this loop we do use the iteration variable. Instead of simply adding one to the count as in the previous loop, we add the actual number (3, 41, 12, etc.) to the running total during each loop iteration. If you think about the variable total, it contains the "running total of the values so far". So before the loop starts total is zero because we have not yet seen any values, during the loop total is the running total, and at the end of the loop total is the overall total of all the values in the list.

As the loop executes, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator.

Launch Exercise

Neither the counting loop nor the summing loop are particularly useful in practice because there are built-in functions len() and sum() that compute the number of items in a list and the total of the items in the list respectively.

Code Output
total_count = len([3, 41, 12, 9, 74, 15])
print(total_count)
6
total_sum = sum([3, 41, 12, 9, 74, 15])
print(total_sum)
154

Maximum and Minimum Loop Examples

To find the largest value in a list or sequence, we construct the following loop:

largest = None
print 'Before:', largest

for itervar in [3, 41, 12, 9, 74, 15]:
    if largest is None or itervar > largest :
        largest = itervar
    print 'Loop:', itervar, largest

print 'Largest:', largest

When the program executes, the output is as follows:

Before: None
Loop: 3 3
Loop: 41 41
Loop: 12 41
Loop: 9 41
Loop: 74 74
Loop: 15 74
Largest: 74

The variable largest is best thought of as the "largest value we have seen so far". Before the loop, we set largest to the constant None. None is a special constant value which we can store in a variable to mark the variable as "empty".

Before the loop starts, the largest value we have seen so far is None since we have not yet seen any values. While the loop is executing, if largest is None then we take the first value we see as the largest so far. You can see in the first iteration when the value of itervar is 3, since largest is None, we immediately set largest to be 3.

After the first iteration, largest is no longer None, so the second part of the compound logical expression that checks itervar > largest triggers only when we see a value that is larger than the "largest so far". When we see a new "even larger" value we take that new value for largest. You can see in the program output that largest progresses from 3 to 41 to 74.

At the end of the loop, we have scanned all of the values and the variable largest now does contain the largest value in the list.

Launch Exercise

To compute the smallest number, the code is very similar with one small change:

smallest = None
print 'Before:', smallest

for itervar in [3, 41, 12, 9, 74, 15]:
    if smallest is None or itervar < smallest:
        smallest = itervar
    print 'Loop:', itervar, smallest

print 'Smallest:', smallest

Again, smallest is the "smallest so far" before, during, and after the loop executes. When the loop has completed, smallest contains the minimum value in the list.

Launch Exercise

Again as in counting and summing, the built-in functions max() and min() make writing these exact loops unnecessary.

Code Output
maximum = max([3, 41, 12, 9, 74, 15])
print(maximum)
74
minimum = min([3, 41, 12, 9, 74, 15])
print(minimum)
3

Input Validation Loop Example

Program end users are incompetent.  They rarely read directions and they will come up with an infinite number of ways to break your program.  We'll learn more about ways of trapping many types of errors, but for now, we can use an input validation loop to steer the end users in the right direction.

Example: Candy Bar Ordering System

This programs accepts the number of candy bars a user wishes to order.

candy_bars = int(input("Enter number of candy bars desired: "))

while candy_bars < 0:
    print("You can\'t order negative candy bars!")
    candy_bars = int(input("Enter number of candy bars desired: "))

if candy_bars == 0:
    print("I'm sorry you don't like candy bars")

elif candy_bars > 20:
    print("That's a big order!")

elif candy_bars > 50:
    print("You sure like candy!")

print("Thank you for ordering", candy_bars, "candy bars!\n")

Output:

First Iteration

Enter number of candy bars desired: -1
You can't order negative candy bars!
Enter number of candy bars desired: 2
Thank you for ordering 2 candy bars!

Second Iteration

Enter number of candy bars desired: 22
That's a big order!
Thank you for ordering 22 candy bars!

First Iteration

Enter number of candy bars desired: 122
You sure like candy!
Thank you for ordering 122 candy bars!

How It Works

We'll focus on the input validation loop.

Code Output
candy_bars = int(input("Enter number of candy bars desired: ")) Enter number of candy bars desired:

We assign the variable candy_bars to accept the input from the end user.

Code Output
while candy_bars < 0:
    print("You can\'t order negative candy bars!")
    candy_bars = int(input("Enter number of candy bars desired: "))

Varies depending on the user’s input

This is our input validation loop.  Our condition is that candy_bars is less than 0 (or a negative number).  So if our end user turns out to be a wise guy and plugs in -1, this while loop will trigger, yell at the end user, and prompt them for another entry.  If the end user continues to enter negative numbers, the loop will continue until the condition (negative number) is no longer satisfied.  Then the rest of the code continues. 

If the users does the right thing and enters a number greater than or equal to 0 from the beginning, then the while loop is skipped altogether.

Pretty neat, huh?

Launch Exercise