51 exam-style questions plus unlimited generated ones on this topic, at up to four difficulty levels, with full mark schemes. Notes and past-paper booklets are open to everyone. Practice needs a free account.
Or take a quick quiz: 11 questions on this subtopic in GCSE Computer Science (Edexcel), marked as you tap.
Subprograms let you break a program into named, reusable parts. You need to use built-in and library subprograms (such as len() and random.randint()), write your own functions and procedures, with or without parameters, and explain the difference between local and global variables.
Key facts
Subprogram: a named block of code for one task, run when it is called
Function: returns a value with return. Procedure: does not return a value
Parameter: variable in the definition. Argument: value passed in the call
Local variable: created in a subprogram, only usable there
Global variable: created in the main program, can be read anywhere
Notes
Subprograms
A subprogram is a named block of code that carries out one task. It only runs when it is called.
Pre-existing subprograms are already written: built-in ones such as len(),print(),int() and round(), and library ones that you import. User-devised subprograms are ones you write.
Benefits: code is written once and reused, so the program is shorter; each subprogram can be tested on its own; a big problem is decomposed into parts that different programmers can write; the main program is easier to read and maintain.
Functions and procedures
diagram
A function returns a value using return. A procedure carries out a task, such as printing, and does not return a value.
Both may or may not take parameters: the variables in brackets in the definition, which receive values when the subprogram is called. The values passed in are called arguments.
area is a function: area(5, 3) returns 15, which is stored in size.greet is a procedure: it outputs Hello Mo and returns nothing.
Arguments are matched to parameters in order: length receives 5 and width receives 3.
Arguments are passed into the parameters in order; the returned value replaces the call.
Libraries
Import a library at the start of the program, e.g. import random or import math.
random.randint(1, 6) gives a random whole number from 1 to 6: both ends are included.
math.sqrt(49) gives 7.0, math.floor(4.7) gives 4 and math.ceil(4.2) gives 5.
Library subprograms save time and have already been tested, so they are reliable.
Local and global variables
diagram
A local variable is created inside a subprogram. It can only be used inside that subprogram and only exists while the subprogram is running. Parameters are local too.
A global variable is created in the main program, outside any subprogram, and can be read anywhere in the program.
The two local variables called count are separate and only exist while their subprogram runs.
Local variables are better practice: the same name can be used in different subprograms without clashing, the memory is freed when the subprogram ends, and each subprogram is self-contained, so it is easier to test and reuse. Pass data in with parameters and out with return.Grade 7+ only
If a subprogram assigns a value to a variable, Python treats it as a new local variable, even when a global variable has the same name, so the global variable does not change. Grade 8+ only
How to answer each type of question
Functions, procedures and benefits
2 to 4 marksGrade 4
For the difference, say what each one does: a function returns a value, a procedure does not.
For a benefit, give the benefit and a reason, e.g. 'can be reused, so the code only has to be written and tested once'.
Example. (a) State the difference between a function and a procedure. (2) (b) Give two benefits of using subprograms in a program. (2)
Show the model answerHide the model answer
(a) A function returns a value to the part of the program that called it (1); a procedure carries out a task but does not return a value
(1).
(b) Any two, e.g. the code can be reused without writing it again (1); each subprogram can be tested on its own, so errors are easier to find (1); different programmers can write different subprograms at the same time; the program is easier to read and maintain.
Use a library subprogram
2 to 4 marksGrade 5
Import the library at the start of the program.
Write the library name, a dot, then the subprogram, e.g. random.randint().
Remember that randint includes both of its end values.
Example. (a) Write a program that simulates rolling two six-sided dice and outputs the total of the two dice. (3) (b) State the smallest and the largest total your program could output. (1)
Imports the random library (1); generates two random whole numbers from 1 to 6 (1); outputs their total
(1).
(b) 2 and 12
(1)
Trace calls to a function
2 to 4 marksGrade 5
Match each argument to its parameter, in order.
Work through the function body and find the value that is returned.
Put the returned value back where the function was called, then carry on.
Example.
01 def calc(a, b):
02 result = a * 2 - b
03 return result
04
05 x = calc(6, 4)
06 y = calc(x, 3)
07 print(x, y)
(a) State the output of line 07. (2) (b) Identify one local variable in the function calc. (1)Show the model answerHide the model answer
(a) 8 (1)13 (1), output as 8 13
(b) result (1). Also accept a or b: parameters are local variables.
Write a function
3 to 5 marksGrade 7
Start with def, the exact name from the question and the parameters in the order given.
Calculate the result using the parameters, not input().
Use return to send the result back. Do not print it unless the question asks you to.
Example. Write a function discount(price, percent) that returns the price after a percentage discount has been taken off. For example, discount(40, 25) returns 30.0. (4)
A def line with the name and the two parameters in the correct order (1); works out the amount of the discount, price * percent / 100 (1); subtracts it from the price (1); returns the result rather than printing it (1).
Explain local and global variables
3 to 4 marksGrade 8
State the output by tracing the code.
Say where each variable is created: inside the subprogram (local) or in the main program (global).
Explain that assigning to a name inside a subprogram creates a separate local variable, so the global one is unchanged.
State the output of the program and explain why the two values of total are different. (4)Show the model answerHide the model answer
Output: In reset: 0 then Main: 100
(1).
The total in line 04 is a local variable, created inside reset (1). It is a different variable from the global total created in line 01 (1). Changing the local variable does not change the global one, so line 08 still outputs 100
(1).
Don’t lose marks
Using print() instead of return in a function, so the program that called it gets no value back.
Calling a function and not using the result, e.g. writing area(5, 3) on its own line instead of size = area(5, 3).
Forgetting import random, or writing randint(1, 6) without random. in front: a runtime error.
Passing arguments in the wrong order, so each parameter receives the wrong value.
Thinking a subprogram changes a global variable just by assigning to a variable with the same name.
Defining a subprogram but never calling it, so its code never runs.
More tips
Memory tricks
A function is like a calculator: it hands back an answer. A procedure is like a printer: it does a job and hands nothing back.
Parameters are placeholders in the definition; arguments are the actual values in the call.
randint(1, 6) is a normal dice: both ends are included.
Local variables live and die inside their subprogram.
Exam technique
When asked to write a function, include def, the parameters named in the question and a return statement.
Use the subprogram name and parameters exactly as given in the question, in the same order.
For benefits of subprograms, give a reason, not just a word: 'reused, so it only has to be written and tested once'.
When explaining scope, say where the variable is created and where it can be used.
What each grade needs
What you need to be able to do, from the first marks up to the top grade.
Grade 3
Call built-in subprograms such as len()Use pre-existing subprograms such as len(), print(), int() and round() with the right arguments.
Grade 4
Tell functions and procedures apartA function returns a value; a procedure carries out a task and does not return a value.
Grade 5
Import and use library subprogramsE.g. import random, then use random.randint(1, 6) for a dice roll.
Grade 5
Give benefits of using subprogramsCode can be reused, tested on its own and is easier to read and maintain.
Grade 6
Write a procedure that takes parametersDefine it with def, pass values in when you call it, and let it carry out its task.
Grade 7
Write a function that returns a valueTake parameters, calculate a result, return it and use the returned value in the main program.
Grade 8
Explain local and global variablesSay where each variable can be used and why local variables are better practice.
Quick recall
Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.
State the keyword used to start the definition of a subprogram in Python.
State the smallest value and the largest value that the program could output.
Smallest 1, largest 6
Give a reason why double and addTen are functions and not procedures.
They each return a value to the code that called them.
Write a procedure showStars(n) that outputs a line of n stars.
def showStars(n):
print("*" * n)
State the Python keyword that is used to start the definition of a subprogram.
def
Sample questions
Written for this site in the style of Edexcel exam questions. They are not taken from real past papers.
Question 1Easy5 marks
Programs are often written using subprograms.
(a) Define the term 'subprogram'.
[1]
(b) Identify the built-in Python function.
[1]
len()
calculateTotal()
getInitials()
showMenu()
(c) Give two benefits of using subprograms when writing a program.
[2]
(d) State the keyword used to start the definition of a subprogram in Python.
[1]
Show the answer and mark scheme
(a)Answer: A named, self-contained block of code that carries out a specific task and can be called from other parts of the program.
a named / self-contained block of code that carries out a specific task (and can be called / used from elsewhere in the program)
(b)Answer:len()
(c)Answer: The code can be called many times without being written out again, and each subprogram can be tested on its own.
code can be reused / called many times without repeating it (so the program is shorter)
each subprogram can be tested / debugged separately
the program is easier to read / maintain (a change is made in one place)
different programmers can work on different subprograms at the same time
subprograms can be reused in other programs / stored in a library
(d)Answer:def
def
Question 2Medium7 marks
Look at this program.
01 def double(n):
02 return n * 2
03
04 def addTen(n):
05 return n + 10
06
07 x = double(3)
08 y = addTen(x)
09 z = double(addTen(1))
10 print(x, y, z)
(a) State the output of the program.
[3]
(b) Give a reason why double and addTen are functions and not procedures.
[1]
(c) State the value of double(double(double(1))).
[1]
(d) Write a function triple(n) that returns three times the value of its parameter.
[2]
Show the answer and mark scheme
(a)Answer:6 16 22
6 (x)
16 (y)
22 (z)
(b)Answer: They each return a value to the code that called them.
they return a value (to the code that called them)
(c)Answer: 8
8
(d)Answer:
def triple(n):
return n * 3
a def line for triple with one parameter
returns (not prints) the parameter multiplied by 3
Question 3Hard8 marks
A museum charges £12.50 for each adult ticket and £6.00 for each child ticket. Members get 10% off the total cost.
(a) Write a Python function calculateCost(adults, children, member) that returns the total cost of the tickets in pounds. The parameter member is True if the customer is a member and False if not.
[4]
(b) State the value returned by calculateCost(2, 3, True).
[1]
(c) Write the main program. It must input the number of adults, the number of children and whether the customer is a member (Y or N). It must then call calculateCost and output the cost rounded to 2 decimal places.