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?
- Hint 1: What would you have to change if the quiz grew to 80 questions?
- Hint 2: Which words would you use to ask for “do this 50 times, with a number that goes up”?
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?
- Hint 1: The word range(5) suggests five of something.
- Hint 2: Python often counts from 0.
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.
| Python | Numbers, 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
| Python | Numbers, 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
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?
- Hint 1: Work out savings after each pass, and test savings < 40 before every pass.
- Hint 2: Does the loop test the condition before or after running its instructions?
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.
| Pass | savings at the start | savings < 40 ? | savings after | weeks after |
|---|---|---|---|---|
| 1 | 10 | yes | 25 | 1 |
| 2 | ||||
| Check | - | - |
Show the completed table
| Pass | savings at the start | savings < 40 ? | savings after | weeks after |
|---|---|---|---|---|
| 1 | 10 | yes | 25 | 1 |
| 2 | 25 | yes | 40 | 2 |
| Check | 40 | no | - | - |
The first row is given. The program then shows 2 40.
Check your understanding
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?
- Hint 1: In Lesson 10 an array’s index could start at 0 or 1. What would each choice give here?
- Hint 2: len is short for length.
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
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.
| score | total after adding it |
|---|---|
| 7 | 7 |
| 9 | |
| 4 |
Show the completed table
| score | total after adding it |
|---|---|
| 7 | 7 |
| 9 | 16 |
| 4 | 20 |
The total starts at 0 before the loop. The first row is given.
Check your understanding
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?
- Hint 1: What if you spot a mistake in the rule after copying it?
- Hint 2: Think of the subroutines of Lesson 9: a named block that is written once.
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.
Do not confuse: print and return
- 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
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 0Check your understanding
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?
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: Start with score as 0, and use index 0 for the first question.
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.
| i | answers[i] | key[i] | mark(...) gives | score after |
|---|---|---|---|---|
| 0 | b | b | 1 | 1 |
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 |
Show the completed table
| i | answers[i] | key[i] | mark(...) gives | score after |
|---|---|---|---|---|
| 0 | b | b | 1 | 1 |
| 1 | a | d | 0 | 1 |
| 2 | a | a | 1 | 2 |
| 3 | c | c | 1 | 3 |
| 4 | d | b | 0 | 3 |
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
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
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]).
Apply it
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.
Work this out on paper or the board first. Nothing here is marked: compare yours with the model answer.
- Hint 1: Start a count at 0 before the loop, as when counting in pseudocode.
- Hint 2: Loop over the items, and use an if to add 1 to the count.
Show a model answer
def count_high(scores, limit):
count = 0
for score in scores:
if score > limit:
count = count + 1
return countFor 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
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:rangestops 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.appendadds an item andlengives the length. An index that is too big gives anIndexError. - A function is written once with
def. It receives values through its parameters and hands back a return value withreturn.printonly 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.
A sequence of precise steps that solves a problem or completes a task.
A loop that repeats a fixed number of times, known before it starts. In pseudocode it is a FOR … NEXT loop.
The everyday number system with ten digits, 0 to 9, in which each column is worth ten times the column to its right.
A subroutine that works out one value and returns it, to be used in an expression. It is defined with FUNCTION … RETURNS … ENDFUNCTION and ends with RETURN.
The number, written in square brackets after an array’s name, that says which element is meant.
In Python, an ordered collection of values kept under one name, written in square brackets, which can grow and shrink while the program runs.
A set of instructions that is repeated, either a fixed number of times or until a condition says to stop.
One of the numbers inside a model that are set during training. Together they hold the patterns the model learnt.
A variable named in a subroutine’s definition that receives a value when the subroutine is called. It is usually just called a parameter.
A loop that tests its condition before each repeat, so its instructions may run zero times. In pseudocode it is a WHILE … ENDWHILE loop.
A subroutine that carries out a task and does not return a value. It is defined with PROCEDURE … ENDPROCEDURE and used with CALL.
A precise but language-independent way of writing an algorithm, with set keywords such as IF, WHILE and OUTPUT, that is not tied to any one programming language.
A high-level programming language written as text, popular for learning and for real work, in which indentation shows which lines belong together.
The value that a function hands back to the place that called it, using RETURN.
Your progress on this lesson
Saved in this browser only. It is not sent anywhere, does not follow you to another device, and is lost if you clear this site’s data.
This browser is not allowing the site to save progress, so it will be forgotten when you leave the page.