Home CPSC 110

Looping

Overview

Many algorithms are built on the concept of a loop where you repeat some steps of the algorithm multiple times. For example:

With loops we will be able to write programs that do these kinds of things, and repeat some part of the program over again.

As a first example, consider the "guess the number" game. We could in theory just use if statements to guess all the numbers:


if input("Did you guess 1? ") == "yes":
    print("Got it!")
elif input("Did you guess 2? ") == "yes":
    print("Got it!")
elif input("Did you guess 3? ") == "yes":
    print("Got it!")
elif input("Did you guess 4? ") == "yes":
    print("Got it!")
elif input("Did you guess 5? ") == "yes":
    print("Got it!")
elif input("Did you guess 6? ") == "yes":
    print("Got it!")
elif input("Did you guess 7? ") == "yes":
    print("Got it!")
elif input("Did you guess 8? ") == "yes":
    print("Got it!")
elif input("Did you guess 9? ") == "yes":
    print("Got it!")
elif input("Did you guess 10? ") == "yes":
    print("Got it!")

However, this is clearly kind of repetitive. It also isn't scalable, if we wanted to write a program that would guess a number from 1 to 100, that would be a lot of typing! Instead we should use a loop.


While Loops

The simplest loop in Python is the while loop. The while loop has the following form:


while condition
    line 1
    line 2
    ...

When Python executes a while loop, it starts with checking the condition. If the condition is true, then it executes the body of the loop. Then control goes back to the top of the loop, and Python checks the condition again. If it's still true, the body of the loop is executed again. This continues again and again until the condition is False.

We can use a loop to implement the guess a number as follows:


# start by asking for 1
number = 1
answer = input("Did you guess " + str(number) + "?")

# keep doing the loop until the answer is yes
while answer != "yes":
    number = number + 1
    answer = input("Did you guess " + str(number) + "?")

# when we are done the loop it means we got it
print("Got it!")

This program will keep looping until the user enters "yes". At that point, the condition becomes False and so the loop exits.


Example: Checking Input

We've talked about how to use if statements to check if user input is valid. For instance, this program will check if the user enters a negative number for their age:


age = int(input("How old are you? "))

if age < 0:
    print("Hey, your age can't be negative!")
    age = int(input("How old are you for real? "))

print("You are", age, "years old.")

However, the problem is someone could put in a negative twice.

How could we use a loop to keep on asking them until they get it right?

We can do it by simply replacing if with while. Now, the program will keep asking the user for data until it is greater than or equal to 0.


age = int(input("How old are you? "))

while age < 0:
    print("Hey, your age can't be negative!")
    age = int(input("How old are you for real? "))

print("You are", age, "years old.")

Infinite Loops

One danger when creating loops is that the condition might never become True. For example, there's a mistake in the program below which causes this:


number = 1

while number < 10:
    print(number)
    numer = number + 1

print("All done!")

Because of our typo, the variable number never reaches 10, so the condition stays 10 forever. This is called an infinite loop and is a common programming mistake.

An infinite loop in the Python shell can usually be stopped by hitting "Ctrl-C".


Example: Running Total

How could we write a program which computes a running total? The program should ask the user how many items they want to add. Then it should ask them to enter that many items and add them up, printing the total value at the end.


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

while loops < items:
    next_value = int(input("What is the next value? "))
    total = total + next_value
    loops = loops + 1

print("The total is", total)

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