Study Guide

Python Loops, Lists and Functions

How to repeat instructions with for and while, keep many values in a list, and split a program into functions, built up step by step into a small quiz-marking program in Python.

Lesson 5.19 Algorithms and Programming

For: Key Stage 3 learners (about ages 12 to 14) who have written first Python programs, and Cambridge IGCSE Computer Science learners wanting the same ideas in Python

Stage: Think

Fifty lines of the same thing

A fictional school quiz has 50 questions, and the program should show a heading before each one: “Question 1”, “Question 2”, and so on up to “Question 50”.

Think it through

You could write 50 print lines, one for each heading. Why is that a poor way to write the program, and what would you want the language to let you say instead?

Show a model answer

Fifty nearly identical lines are slow to type, easy to get wrong, and have to be edited line by line if the quiz changes size. It would be better to say “repeat this instruction 50 times, with a counter going from 1 to 50”. That is a loop, which you met in pseudocode as a FOR loop.

Stage: Predict

Repeating with for and range

Python’s count-controlled loop is written with for and range:

for number in range(5):
    print(number)

Think it through

Predict what this program shows. How many lines does it show, what is the first number and what is the last? Are you surprised by either?

Show what happens

It shows five lines: 0, 1, 2, 3 and 4. The first number is 0 and the last is 4, not 5. range(5) makes the numbers from 0 up to, but not including, 5.

number is the loop variable: it takes each value in turn, and the indented lines run once for each. A loop repeats instructions; the colon and the indent work just as they did for if. range follows one rule: it stops before its last number.

  • range(5) gives 0, 1, 2, 3, 4 (it starts at 0 by default).
  • range(1, 6) gives 1, 2, 3, 4, 5 (the start, then the stop-before number).
  • range(2, 12, 3) gives 2, 5, 8, 11 (a third number is the step).

Do not confuse: FOR in pseudocode and for in Python

Does it include the last number?FOR Index ← 1 TO 5
Yes. It runs for 1, 2, 3, 4 and 5.Five times, and Index reaches 5.
Does it include the last number?for index in range(1, 5)
No. It stops before 5, so it runs for 1, 2, 3 and 4.Four times. Use range(1, 6) for 1 to 5.

The most common slip is range(1, 5) when 1 to 5 is meant.

The numbers each loop gives its loop variable
PythonNumbers, in order
range(5)0 1 2 3 4
range(1, 5)
range(3, 8)
range(2, 12, 3)
range(10, 0, -3)

    Show the completed table
    PythonNumbers, in order
    range(5)0 1 2 3 4
    range(1, 5)1 2 3 4
    range(3, 8)3 4 5 6 7
    range(2, 12, 3)2 5 8 11
    range(10, 0, -3)10 7 4 1

    The first row is given. If the start is not below the stop (and the step is positive), the loop does not run at all.

    Check your understanding

    Which loop shows the headings Question 1 to Question 50, using print(“Question”, number)?
    Show the answer

    Answer: C. for number in range(1, 51):

    For the numbers 1 to N, write range(1, N + 1).

    Stage: Predict

    Repeating until something changes: while

    A fictional pupil has £10 saved and adds £15 each week, and wants to know how many weeks it takes to have at least £40.

    savings = 10
    weeks = 0
    while savings < 40:
        savings = savings + 15
        weeks = weeks + 1
    print(weeks, savings)

    Think it through

    Predict what the program shows on its last line. How many times does the loop run, and what makes it stop?

    Show what happens

    It shows 2 40. After the first pass savings is 25 and weeks is 1; after the second, savings is 40 and weeks is 2. Then savings < 40 is false (40 is not less than 40), so the loop stops. A while loop checks its condition before each pass, as a pre-condition loop does in pseudocode.

    Tracing the savings program
    Passsavings at the startsavings < 40 ?savings afterweeks after
    110yes251
    2
    Check--

      Show the completed table
      Passsavings at the startsavings < 40 ?savings afterweeks after
      110yes251
      225yes402
      Check40no--

      The first row is given. The program then shows 2 40.

      Check your understanding

      A programmer forgets the line savings = savings + 15 inside the loop. What happens when the program runs?
      Show the answer

      Answer: A. The loop never stops, because savings stays 10 and 10 < 40 is true every time.

      A loop that never stops is an infinite loop. In an editor it can be stopped with the stop button or Ctrl+C.

      Use for when you know in advance how many times to repeat, such as 50 headings. Use while when you repeat until something happens, such as savings reaching a target. A while loop can run zero times, if its condition is false at the start.

      Stage: Discover

      Keeping many values together: lists

      A fictional pupil keeps a list of three pets in a variable, written in square brackets, with commas between the items:

      pets = ["cat", "dog", "fish"]
      print(pets[1])
      print(len(pets))

      Think it through

      Predict the two lines this shows. What does the number in the square brackets, in pets[1], seem to mean?

      Show what happens

      It shows dog, then 3. The number in square brackets is the index of an item, its position; in a Python list the first item has index 0, so pets[0] is cat, pets[1] is dog and pets[2] is fish. len(pets) is the number of items, 3.

      A list keeps several values, in order, under one name. Each item is found by its index, which starts at 0, so the last item of a list of N items has index N - 1. A list is like the one-dimensional array of Lesson 10, but it is always counted from 0, and it can grow: pets.append("bird") adds an item at the end, making the list four items long.

      Asking for an index that is not there is a mistake: pets[3] on a list of three items stops the program with IndexError: list index out of range.

      Check your understanding

      A list holds 4 items. What is the index of the last item?
      Show the answer

      Answer: D. 3, because the indexes run from 0 to 3, so the last is len minus 1.

      The index of the last item is len(pets) - 1; asking for pets[len(pets)] is always an IndexError.

      Stage: Explain

      Looping over a list

      There are two ways to go through a list. The first gives the loop variable each item in turn:

      scores = [7, 9, 4]
      total = 0
      for score in scores:
          total = total + score
      print(total)

      The second gives it each index, with range(len(...)), so that the program can use the position too:

      pets = ["cat", "dog", "fish", "bird"]
      for i in range(len(pets)):
          print(i, pets[i])

      range(len(pets)) is range(4), which gives 0, 1, 2 and 3, exactly the indexes of the list.

      The first loop, one item at a time
      scoretotal after adding it
      77
      9
      4

        Show the completed table
        scoretotal after adding it
        77
        916
        420

        The total starts at 0 before the loop. The first row is given.

        Check your understanding

        What is the last line shown by the second program, the one that prints i and pets[i]?
        Show the answer

        Answer: B. 3 bird, because the last index is 3.

        Use for item in list when the position does not matter, and range(len(list)) when it does.

        Stage: Discover

        Giving a job a name

        In the quiz, the rule for marking an answer is the same for every question: one mark if the answer given equals the right answer, otherwise none.

        Think it through

        The marking rule takes four lines of Python. The quiz has five questions, so the lines would be copied five times. What could go wrong? What would you prefer to be able to do?

        Show a model answer

        Copies can be pasted wrongly, and a mistake in the rule would have to be corrected in five places. It would be better to write the rule once, give it a name, and use it for each question. That is a subroutine, and in Python it is written with def.

        A function is a named block that is written once with def and can be used whenever it is needed. Names in brackets after the function’s name are its subroutine parameters, usually just called parameters: places that receive the values the function is given when it is used. A function hands back a result with return, its return value.

        def double(number):
            return number * 2
        
        print(double(4))
        print(double(double(3)))

        This shows 8 and then 12. In double(4) the value 4 is given to the parameter number, the function works out number * 2, and return hands back 8, which print then shows. A function that does a job but has no return, such as one that only prints, is what pseudocode calls a procedure.

        Where does the value go?print
        Shows the value on the screen, for a person to read. The program cannot use it afterwards.print(double(4)) shows 8.
        Where does the value go?return
        Hands the value back to the place that used the function, so the program can use it.total = total + double(4) adds 8 to total.

        A function that only prints gives back the special value None.

        Check your understanding

        A function is meant to give back the larger of two numbers so that a program can add it to a total. Which ending of the function is right?
        Show the answer

        Answer: B. return the larger of a and b, so the program can use the value.

        If a program needs to use the result, the function must return it.

        Stage: Explain

        Building the quiz marker: one function

        Now build a small program in three steps. Step one is the marking rule as a function. It has two parameters, the answer given and the right answer, and returns 1 for a correct answer and 0 otherwise.

        def mark(given, correct):
            if given == correct:
                return 1
            else:
                return 0

        Check your understanding

        What do mark(“b”, “b”) and mark(“a”, “d”) give back?
        Show the answer

        Answer: A. 1 for the first call and 0 for the second.

        Writing the rule once means a mistake can be corrected in one place.

        Stage: Experiment

        Building the quiz marker: a loop over two lists

        Step two keeps the right answers in one list and a pupil’s answers in another, in the same order, and uses a loop and mark to build up the score.

        key = ["b", "d", "a", "c", "b"]
        answers = ["b", "a", "a", "c", "d"]
        score = 0
        for i in range(len(key)):
            score = score + mark(answers[i], key[i])
        print("Score:", score, "out of", len(key))

        Think it through

        Trace the loop on paper: for each value of i, write answers[i], key[i], what mark gives, and the score afterwards. What does the last line show?

        Show a model answer

        At i = 0 the answers are “b” and “b”, mark gives 1, score 1. At i = 1: “a” and “d”, 0, score 1. At i = 2: “a” and “a”, 1, score 2. At i = 3: “c” and “c”, 1, score 3. At i = 4: “d” and “b”, 0, score 3. The last line shows Score: 3 out of 5.

        The marking loop, one question at a time
        ianswers[i]key[i]mark(...) givesscore after
        0bb11
        1
        2
        3
        4

          Show the completed table
          ianswers[i]key[i]mark(...) givesscore after
          0bb11
          1ad01
          2aa12
          3cc13
          4db03

          The first row is given. The final score is 3 out of 5.

          Stage: Explain

          Building the quiz marker: a second function

          Step three adds a second function that turns the score into a grade: 80% or more is a Merit, 50% or more a Pass and anything lower is Try again.

          def grade(score, total):
              percentage = score * 100 / total
              if percentage >= 80:
                  return "Merit"
              elif percentage >= 50:
                  return "Pass"
              else:
                  return "Try again"
          
          print(grade(score, len(key)))

          The whole program is now mark, then grade, then the lists, the loop and the two print lines. Each function does one job and can be tested alone.

          Check your understanding

          Using the score of 3 out of 5, what does the last line of the program show, and why?
          Show the answer

          Answer: C. Pass, because 3 * 100 / 5 is 60, which is at least 50 but below 80.

          The percentage is 60.0. Python’s / gives a decimal, which is fine for these comparisons.

          Stage: Apply

          Spot the mistake

          Sam (fictional) changes the loop of the quiz program to for i in range(len(key) + 1):, hoping to include every question.

          Apply it

          What happens when Sam’s program runs, and why?
          Show the answer

          Answer: B. It stops with an IndexError, because i reaches 5 and the lists have indexes 0 to 4 only.

          range(len(list)) gives exactly the indexes of the list. Adding to its stop number goes past the end.

          Priya (fictional) writes the marking function like this:

          def mark(given, correct):
              if given == correct:
                  print(1)
              else:
                  print(0)

          and leaves the loop as score = score + mark(answers[i], key[i]).

          What happens when the program runs?
          Show the answer

          Answer: C. It stops with a TypeError, because the function returns None and score cannot add that.

          A function used in a calculation must return its value; print only shows it.

          Stage: Apply

          Write a function of your own

          Think it through

          Write a function count_high(scores, limit) that returns how many of the numbers in the list scores are greater than limit. Then say what count_high([7, 9, 4, 10, 6], 6) gives.

          Show a model answer
          def count_high(scores, limit):
              count = 0
              for score in scores:
                  if score > limit:
                      count = count + 1
              return count

          For the list 7, 9, 4, 10, 6 and the limit 6, the scores greater than 6 are 7, 9 and 10, so the function returns 3. The 6 is not greater than 6. The count starts at 0 before the loop, and return is after the loop, at the same indent as for, so that it runs once, at the end.

          Stage: Consolidate

          Show what you know

          Think it through

          Explain why the quiz program is easier to read, test and change when the marking rule and the grading rule are separate functions, compared with one long program. Use one example change.

          Show a model answer

          A good answer says that each function does one job and has a name, so a reader can see what the program does at a glance, a function can be tested alone with known inputs (such as mark("a", "d") giving 0), and a change is made in one place. For example, changing the Merit boundary from 80 to 75 means editing one line in grade, and the loop and mark do not change.

          Apply it

          A fictional canteen program has prices = [2, 3, 5] and a function total(prices) that loops over the list adding each price to a running total. Which statement is correct about the function’s last line?
          Show the answer

          Answer: A. It should be return running_total, at the indent of the for, so that it runs once after the loop.

          Put return after a loop when the whole loop must finish first.

          Think it through

          Which part of this lesson are you least sure about? Write one question you would ask your teacher.

          Show a model answer

          There is no wrong answer. Two questions worth asking: “how do I know which number to put in range?” (the stop number is one more than the last number wanted) and “when do I use return and when print?” (return when the program needs the value; print to show it to a person).

          • A loop repeats instructions. for number in range(1, 6) gives 1 to 5: range stops before its last number, starts at 0 if no start is given, and can take a step as a third number.
          • while condition: repeats as long as the condition is true, checked before every pass. Something in the loop must change what the condition tests, or the loop never stops.
          • A list keeps values in order under one name. Its index starts at 0, so the last item is len(list) - 1. append adds an item and len gives the length. An index that is too big gives an IndexError.
          • A function is written once with def. It receives values through its parameters and hands back a return value with return. print only shows a value; a function used in a calculation must return it.
          • A modular program is built from small functions, each with one job, a loop over lists, and a few lines that put them together.

          Sources and scope

          • What this lesson is. The nineteenth lesson of the Algorithms and Programming module, written for this site. It carries the loops, arrays and subroutines of Lessons 5, 9 and 10 into Python. Its curriculum links are provisional and imply no review or endorsement by any examination board; the Cambridge points are marked as supporting because the examinations are answered in pseudocode.
          • Original material. The school quiz, the pet list, the savings, the canteen prices, and Sam and Priya are fictional, written for this lesson. Every program was run in Python and its output, and the error messages named, were checked.
          • Simplified on purpose. Lists hold items of one kind and are not copied, sliced or sorted. Other list operations, dictionaries, local and global variables in Python, default parameters and recursion are not taught. A function is shown returning one value.
          • Left to later lessons. Tables of data (lists of lists), reading and writing files, and programs that make several decisions about the data they hold.