KS3National Curriculum Y8.3 30 min read 10 question quiz 17 exam marks

Python: Loops, Lists and Functions

Moving beyond the basics into for loops, while loops, lists, functions and simple validation. This is the point where you can start writing real programs.

Loops

for loops

A for loop repeats a known number of times.

Python
for i in range(5):
    print("Hello", i)

This prints Hello 0 through to Hello 4. That is five times, but it never reaches 5.

Python
range(5)        # 0, 1, 2, 3, 4
range(1, 6)     # 1, 2, 3, 4, 5
range(0, 10, 2) # 0, 2, 4, 6, 8

while loops

A while loop repeats for as long as a condition is true. Use it when you do not know how many repetitions are needed.

Python
password = ""
while password != "letmein":
    password = input("Enter the password: ")
print("Welcome")
Infinite loops

If nothing inside the loop can make the condition false, it runs forever. Always check that something inside the loop changes the value being tested.

Choosing which loop

SituationLoop
Repeat exactly 10 timesfor
Loop through every item in a listfor
Keep asking until the input is validwhile
Run until the player quitswhile
for loops, while loops and what the loop variable holdsWhat a loop variable holds on each pass. For i in range five, printing Hello and i, runs five times with i taking the values zero, one, two, three and four, printing Hello 0 through to Hello 4, so it never reaches five. The range function takes a start, a stop and a step, and the stop value is never included: range five gives zero to four, range one to six gives one to five, and range zero to ten step two gives zero, two, four, six and eight. A while loop instead repeats as long as its condition is true, so a password loop that starts with an empty string keeps asking while the entered password does not equal letmein, and the trace shows the condition true for the empty string, for cat and for dog, and false once letmein is typed, at which point Welcome is printed. Use while when you do not know how many repeats are needed. If nothing inside the loop changes the value being tested, such as a total that stays at zero while the condition checks total less than ten, the loop runs forever.What the loop variable is doing on each passfor i in range(5): print("Hello", i)iprinted0Hello 01Hello 12Hello 23Hello 34Hello 4TRACEfive passesi starts at 0and never reaches 5range(5) gives five numbers starting at zero, which is why the last one is 4range(5)01234range(1, 6)12345range(0, 10, 2)02468start, stop, step. The stop value is never included.range(1, 6) is the one to use when counting 1 to 5password = ""while password != "letmein": password = input("Password: ")print("Welcome")password!= letmein?""True"cat"True"dog"True"letmein"FalseTRACEThe condition is checked before every pass, so a wrong guess simply asks againUse while when you do not know how many repeats you needtotal = 0while total < 10: print(total)# total never changesINFINITE LOOPtotal is 0 forever, so0 < 10 is true forever.The program never ends.Before you run a while loop, find the line inside it that changes the value being tested.If there isn't one, you have written an infinite loop.
In an exam, trace the loop on paper with a two column table. It turns a guess into a method.
for loops count; while loops wait for a conditionTwo kinds of loop. A for loop repeats a set number of times. The code for lap in range of five prints Lap and the lap number, and the picture shows it as a running track with five flags numbered 0 to 4: range of five counts from 0 up to 4, so there are five laps and the value 5 is never reached. A while loop repeats until a condition becomes False. Starting with battery equal to 3, the loop checks battery greater than 0, which is True, so it takes one off the battery and goes round again, checking before every go. At battery 0 the condition is False and the loop stops. If nothing inside the loop ever changes the battery, the condition would stay True for ever, which is an infinite loop.for: repeat a set number of timesfor.py1for lap in range(5):2    print("Lap", lap)outputLap 0 Lap 1 Lap 2 Lap 3 Lap 401234range(5) counts 0, 1, 2, 3, 4: five laps, never 5lap starts at 0, finishes at 4while: repeat until a condition is Falsewhile.py1battery = 32while battery > 0:3    battery = battery - 1battery = 33 > 0 Truebattery = 22 > 0 Truebattery = 11 > 0 Truebattery = 00 > 0 Falsestopsif battery never changed, the loop would never stop12
  1. for repeats a set number of times. range(5) gives 0, 1, 2, 3, 4: five laps.
  2. while repeats until its condition is False, checked before every go round.
Use for when you know how many times. Use while when you only know when to stop.
A for loop that counts, a while loop that waits for a condition, and an infinite loopTwo kinds of loop. A for loop is used when you know how many times: for i in range 5 runs five times with i taking 0, 1, 2, 3 and 4, and then ends by itself. A while loop repeats until something changes: while guess is not cat, ask again, and when the guess is cat it carries on. The number of laps is not known in advance. The classic bug is the infinite loop. With n equal to 5 and while n greater than 0 printing n, if the line that reduces n is forgotten then n never changes, n greater than 0 is always true and the loop never stops. Make sure something inside the loop changes the condition.for: you know how many times1for i in range(5):    print('lap', i)01234i takes 0, 1, 2, 3, 4 and then the loop ends by itselffive laps, counted for youwhile: repeat until something changes2guess = ''while guess != 'cat':    guess = input('Guess? ')print('Correct!')dog!=Trueask againbird!=Trueask againcat!=Falsecarry onchecked every time round, before the body runsThe classic bug: an infinite loop3n = 5while n > 0:    print(n)    # forgot: n = n - 15n never changes, so n > 0 is always trueand the loop never stops: 5, 5, 5, 5 ...make sure something inside the loopchanges the condition
  1. for repeats a counted number of times and stops by itself.
  2. while checks a condition each time and repeats until it is false.
  3. If nothing inside the loop changes the condition, the loop never stops.
Use for when you know the count, and while when you are waiting for something to happen.

Lists

A list stores many values under one name.

Python
scores = [12, 45, 3, 78, 20]
names = ["Aisha", "Ben", "Chloe"]

print(scores[0])      # 12, the first item
print(scores[4])      # 20, the last item
print(len(scores))    # 5
Lists start at 0

The first item is at index 0, so a list of 5 items has indexes 0 to 4. There is no index 5.

Changing a list

Python
scores.append(99)     # add to the end
scores[1] = 50        # change the second item
scores.remove(3)      # remove the value 3
del scores[0]         # remove the item at index 0

Looping through a list

Python
for score in scores:
    print(score)

Useful built in functions

Python
print(sum(scores))         # adds them all up
print(max(scores))         # largest
print(min(scores))         # smallest
print(len(scores))         # how many
print(sorted(scores))      # a sorted copy

average = sum(scores) / len(scores)
A list is a row of numbered lockersA list drawn as a row of numbered lockers, with the code that changes it. The list scores starts with five values, 72, 85, 90, 64 and 78, in lockers numbered from 0. The call append of 88 adds a new locker on the end, so the list now has six items. The assignment scores, bracket, 1, bracket, equals 99 replaces what was in locker 1, the 85, with 99. Reading scores bracket 2 opens locker 2 and finds 90, and len of scores is 6, so the last index is 5, one less than the length. The program prints 90 and 6.lists.py1scores = [72, 85, 90, 64, 78]2scores.append(88)3scores[1] = 994print(scores[2], len(scores))output90 6the item at index 2, then the length720991902643784885appendchangedscores[2]len(scores) is 6, so the last index is 51234
  1. The list holds its items in order, and the first locker is number 0.
  2. append() puts a new item on the end, so the list grows.
  3. Assign to an index to replace what is there. The old value is gone.
  4. scores[2] opens locker 2. len(scores) counts the lockers, so the last index is one less.
Index from 0, and remember the last index is len minus 1.
Five list methods, each shown on the list 45, 78, 12, 90, 33 before and afterFive list methods, each starting from the list 45, 78, 12, 90, 33. append of 60 adds 60 on the end. insert of 1 comma 99 puts 99 at index 1 and the rest move along. remove of 12 takes out the first 12 and the rest close up, leaving 45, 78, 90, 33. pop takes off the last item, 33, and returns it, leaving 45, 78, 12, 90. sort puts the list in place in order, smallest first: 12, 33, 45, 78, 90.scores = [45, 78, 12, 90, 33]each row starts from this list1scores.append(60)4578129033457812903360added to the end2scores.insert(1, 99)4578129033459978129033inserted at index 1, the rest move along3scores.remove(12)457812903345789033the first 12 is removed, the rest close up4scores.pop()457812903345781290the last item is removed and returned: 335scores.sort()45781290331233457890sorted in place, smallest first
  1. append() adds to the end.
  2. insert() puts an item at a position, and the rest move along.
  3. remove() takes out the first item with that value.
  4. pop() removes the last item and gives it back.
  5. sort() orders the list in place.
These methods change the list itself. They do not make a copy.

Functions and validation

Functions

A function is a named block of code you can use over and over.

Python
def area_of_rectangle(width, height):
    return width * height

print(area_of_rectangle(5, 3))     # 15
print(area_of_rectangle(10, 2))    # 20
  • def starts the definition
  • width and height are parameters, the values the function needs
  • return sends an answer back

Some functions do not return anything, they just do something:

Python
def show_menu():
    print("1. Play")
    print("2. Scores")
    print("3. Quit")

show_menu()

Why functions help

  • Write the code once and use it many times
  • Fix a bug in one place instead of ten
  • The program becomes shorter and easier to read
  • Each function can be tested on its own

Validation

Validation checks that input is sensible before the program uses it.

Python
age = input("Enter your age: ")

while not age.isdigit() or int(age) < 0 or int(age) > 120:
    print("Please enter a whole number between 0 and 120.")
    age = input("Enter your age: ")

age = int(age)
print("Thank you")

This loops until the input is acceptable, rather than crashing.

CheckWhat it does
Presence checkSomething has been entered
Range checkThe value is between two limits
Type checkThe data is the right type
Length checkThe right number of characters
A function takes values in and hands a value backA function drawn as a machine. The code defines area with two parameters, w and h, and returns w times h. The line x equals area of 3, 4 calls it: the two arguments, 3 and 4, drop into the machine through the hopper, and the result, 12, comes out of the chute and is stored in x, so print of x shows 12. Parameters are the names the function uses for what it is given, and arguments are the actual values supplied when it is called. Below, a procedure and a function are compared: a procedure does a job, such as printing a greeting, and gives nothing back, while a function hands a value back to the caller with return.area.py1def area(w, h):2    return w * h34x = area(3, 4)5print(x)output12A function is a machinearea(w, h)34arguments in12returnedw and h:parametersProceduredef hello():    print("Hi")does a job, givesnothing backFunctiondef double(n):    return n * 2hands a value backwith return1234
  1. Define it once with def, naming the parameters it will be given.
  2. Call it with arguments. They fill the parameters, w = 3 and h = 4.
  3. return hands the result back to the line that called it.
  4. A procedure does a job. A function also gives a value back.
Parameters are the names in the definition. Arguments are the values in the call.
Validation checks, and what they cannot doSix validation checks, one card each, with a value that is rejected and a value that is accepted. A presence check makes sure something is entered, so an empty entry is rejected. A type check makes sure the data is the right kind, so the letters abc are rejected for an age. A range check keeps a number between limits, so an age of 200 is rejected. A length check makes sure there are enough characters, so pass is too short for a password of eight or more. A format check makes sure the data matches a pattern, so asha dot com is not an email address without an at sign. A lookup check makes sure the value is one of an allowed list, so Funday is not a day of the week. Two cards underneath separate validation from correctness: validation checks data is sensible, not that it is true, so an age of 15 mistyped as 51 passes a range check and is still wrong. Verification checks that data was entered as intended, for example by typing a password twice and comparing.Presencesomething must be entered""AshaTypethe right kind of data"abc"15Rangebetween two limits (0 to 120)20015Lengthenough characters (8 or more)"pass""pass1234"Formatmatches a pattern"asha.com""asha@mail.com"Lookupone of an allowed list"Funday""Friday"1Valid is not the same as trueAge 15 mistyped as 51 is in range,so every check passes and thedata is still wrong.validation checks it is sensible, not that it is trueVerification: typed twicepasswordenter itconfirmand enter it againdo they match?23
  1. Validation checks: presence, type, range, length, format and lookup.
  2. Validation checks that data is sensible. It cannot know whether it is true.
  3. Verification asks the user again, for example with a confirm password box, to catch typing slips.
Validate on the way in, and tell the user what is wrong, not just that something is.

Key terms you must be able to define

for loop
A loop that repeats a known number of times, or once for each item in a collection.
while loop
A loop that repeats for as long as a condition remains true.
List
A data structure that stores many values under one name, accessed by index.
Index
The position of an item in a list, counting from 0.
Function
A named block of code that performs a task and can be called many times.
Parameter
A value passed into a function so it can do its work.
Return
Sending a result back from a function to the code that called it.
Validation
Checking that input is sensible before the program uses it.
Infinite loop
A loop whose condition never becomes false, so it never stops.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

Definefor loop
AnswerA loop that repeats a known number of times, or once for each item in a collection.
Definewhile loop
AnswerA loop that repeats for as long as a condition remains true.
DefineList
AnswerA data structure that stores many values under one name, accessed by index.
DefineIndex
AnswerThe position of an item in a list, counting from 0.
DefineFunction
AnswerA named block of code that performs a task and can be called many times.
DefineParameter
AnswerA value passed into a function so it can do its work.
DefineReturn
AnswerSending a result back from a function to the code that called it.
DefineValidation
AnswerChecking that input is sensible before the program uses it.

Reach the top grade on this topic

The top level in Year 8 Python is about choosing the right tool and explaining why.

Justify your loop choice. "I used a while loop because I do not know how many attempts the user will need to type a valid password."

Use functions before you are told to. If the same three lines appear twice in your program, make them a function. Being able to spot repetition and remove it is exactly what pattern recognition means in practice.

Validate everything the user types. A program that crashes when someone types letters instead of a number is not finished.

  • Explain when to use a for loop and when to use a while loop
  • Write a validation loop that keeps asking until the input is acceptable
  • Write a function with parameters and a return value, and explain each part
  • Loop through a list and calculate the total, average and highest value

Mistakes that cost marks here

Avoid these
  • Thinking range(5) includes 5. It gives 0 to 4.
  • Forgetting that list indexes start at 0, so the last index is one less than the length.
  • Writing a while loop where nothing inside changes the condition, creating an infinite loop.
  • Forgetting to use return, so the function calculates the answer and then throws it away.
  • Initialising a highest score variable to 0 when the values could be negative.
Fun fact

The for loop in Python does not count on its own. It walks through a collection of items, and range() simply makes a collection of numbers for it to walk through. Understanding that makes loops far easier.

Knowledge check

0 of 10 answered
1How many times does for i in range(4) repeat?
2What is scores[0] if scores = [10, 20, 30]?
3Which loop should be used to keep asking until the user types a valid answer?
4What does scores.append(50) do?
5What does the return keyword do in a function?
6What is wrong with while x < 10: print(x) if x is 0?
7How would you find the highest value in a list called marks?
8A list has 7 items. What is the index of the last item?
9What is validation?
10Why are functions useful?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

17 marks
1State the difference between a for loop and a while loop.2 marks
State

Mark scheme0 / 2
  • LA for loop repeats a known number of times
  • LA while loop repeats while a condition is true, and the number of repetitions may not be known
Model answer

A for loop repeats a known, fixed number of times, or once for every item in a collection such as a list. A while loop repeats for as long as a condition remains true, so the number of repetitions is not necessarily known in advance and depends on what happens while the program runs.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Write a Python program that asks the user for five numbers, stores them in a list, and then prints the total and the average.5 marks
Write

Mark scheme0 / 5
  • LCreates an empty list
  • LUses a for loop to repeat five times
  • LTakes input and converts it to a number
  • LAdds each number to the list
  • LCalculates and prints the total and average
Model answer

numbers = [] for i in range(5): value = int(input("Enter a number: ")) numbers.append(value) total = sum(numbers) average = total / len(numbers) print("Total:", total) print("Average:", average) An empty list is created first. The for loop runs five times, and each time it reads a number, converts it from the text returned by input into an integer, and appends it to the list. After the loop the built in sum function adds up the list and dividing by len gives the average.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain what validation is and describe one validation check that could be used when asking for a percentage mark.3 marks
Explain

Mark scheme0 / 3
  • LValidation checks that input is sensible before it is used
  • LNames a suitable check such as a range check
  • LExplains the check, such as ensuring the value is between 0 and 100
Model answer

Validation means checking that the data a user has entered is sensible and in the expected form before the program tries to use it, so that the program does not crash or produce meaningless results. For a percentage mark, a range check would be used to confirm that the value entered is between 0 and 100 inclusive, since a mark of 150 or -20 is impossible. A type check would also be needed to confirm that a whole number has been entered rather than letters, because trying to convert text such as hello into a number would cause the program to crash.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Explain two reasons why a programmer would use functions in a program.4 marks
Explain

Mark scheme0 / 4
  • LCode can be written once and called many times
  • LThis avoids duplication so the program is shorter
  • LIf a change is needed it only has to be made in one place
  • LEach function can be tested on its own, making errors easier to find
Model answer

The first reason is that a function lets code be written once and then used as many times as needed, simply by calling its name. This avoids the same lines being copied out repeatedly, so the program is much shorter and easier to read, and crucially it means that if the code ever needs correcting or changing, the edit is made in one place rather than being repeated everywhere the code appears. The second reason is that functions make a program much easier to develop and test. Each function does one clearly defined job, so it can be tested on its own with different inputs until it is known to work, which makes faults far easier to locate than in one long program where everything is mixed together.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5A program uses while count < 10: and prints count inside the loop, but the program never stops. Explain why and how to fix it.3 marks
Explain

Mark scheme0 / 3
  • LThe value of count is never changed inside the loop
  • LSo the condition remains true forever and the loop never ends
  • LFix by adding a line inside the loop that increases count
Model answer

The loop never stops because nothing inside it changes the value of count. The condition count less than 10 is tested before every repetition, but since count keeps the same value it stays true forever, producing an infinite loop that prints the same number endlessly. The fix is to add a line inside the loop that increases count each time, such as count = count + 1, so that count rises towards 10 and the condition eventually becomes false, allowing the loop to end.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 17