Home CPSC 110

Loop Patterns

Today we will practice programming and go over some common looping patterns.

Accumulator Loops

One very common pattern is called an "accumulator" loop. Here, we have a loop that updates a variable based on its old value, to "accumulate" a bunch of values together.

An example is the running total program we looked at before:

items = int(input("How many items to add? "))
total = 0

for i in range(items):
    next_value = int(input("What is the next value? "))
    total = total + next_value

print("The total is", total)

Here the total variable is the accumulator. It starts at 0, and then adds into this value each time through.

Another example of an accumulator is a program to calculate factorials.

Searching Loops

Another common pattern is a loop that looks for a particular thing at each iteration. For instance, we could search a list for a particular item, or search through a range of numbers to find one with a particular property (like even or prime ones).

These involve a loop with an if statement inside of it to test the property we are looking for. For example, this program looks for numbers that divide the input evenly:

number = int(input("Enter a number: "))

for i in range(2, number):
    if number % i == 0:
        print(number, "is divisible by", i)

Example: Finding the Biggest

Another common example of this sort of pattern is finding the biggest (or smallest) value.

How could we write a program to read in some numbers from the user and keep track of which one was the biggest? The program should keep reading in numbers from the user until a negative value is given. At that point it should stop looping. The program should then print the biggest number the user put in.

num = int(input("Enter a number: "))
biggest = num

while num >= 0:
    num = int(input("Enter a number: "))
    if num > biggest:
        biggest = num

print("The biggest is", biggest)

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.