Procedures and Functions
Procedures and Functions
When writing programs, we should avoid long, repetitive code. Procedures and functions help to
keep our programs simple and short.
What is a procedure?
Just like algorithms, programs are designed to solve a problem. In order to solve the problem, the
program needs to perform several tasks. Code is written to perform each of these tasks.
A procedure is a small section of a program that performs a specific task. Procedures can be used
repeatedly throughout a program.
A real-life example of a procedure is brushing your teeth. There are several steps involved in this
process – getting your toothbrush, squeezing the toothpaste onto the brush, brushing all your teeth,
rinsing your mouth out and putting everything back. Each of these steps isn’t usually described, they
just form part of the whole ‘brushing teeth’ procedure. The next time you need to brush your teeth,
you remember the ‘brushing teeth’ procedure and know exactly what to do.
When writing programs it is very easy to end up with long-winded, repetitive code which is hard to
understand and debug. This is because the same task often needs to be carried out in different places
in the program. Procedures can be used throughout a program, making them simpler and quicker to
code.
Using procedures has an added benefit. If something needs to be changed in a procedure, it only
needs to be changed once, within the procedure code. This change will then appear wherever the
procedure is used in the program. If procedures weren’t used, the code would have to be amended at
every point that it appears in the program.
a name
the program code to perform the task
Indented code tells Python that the code belongs to the procedure.
To call a procedure in Python, simply use its name (include the brackets):
Each time you needed to print out the player information, you could simply call the procedure:
def update_display():
print("Your score: " + str(score))
time.sleep(1)
print("High score: " + str(high_score))
time.sleep(1)
print("Lives remaining: " + str(lives))
time.sleep(1)
Using this procedure greatly reduces the amount of code that has to be included in the program.
What is a function?
A procedure is a small section of a program that performs a specific task. Procedures can be used
repeatedly throughout a program.
A function is also a small section of a program that performs a specific task that can be used
repeatedly throughout a program, but the task is usually a calculation. Functions perform the task
and return a value to the main program.
Both functions and procedures are small sections of code that can be repeated through a program.
The difference between them is that functions return a value to the program where procedures
perform a specific task
While procedures are great for carrying out repetitive tasks, they don’t give any feedback – when
brushing your teeth, you carry out a series of steps and then you’re finished.
Sometimes, feedback – eg an answer or result – is needed. For example, if you’re playing a board
game that uses a dice, you need to roll the dice to see how many moves to make.
A function is just like a procedure, except that you wait to see what the result is.
Using functions has an added benefit. If something needs to be changed in a function, it only needs to
be changed once, within the function code. This change will then appear wherever the function is
used in the program. If functions weren’t used, the code would have to be amended at every point
that it appears in the program.
Writing a function
Writing a function is extremely simple. Every function needs:
a name
Functions in Python
Look at this excerpt from a Python role-playing game programwhich simulates the throwing of a
dice:
import random
sides = int(input("How many sides does the dice have?"))
number = random.randint(1,sides) p
print(number)
Imagine that there is a need to simulate dice throwing many times in this game. A function could be
used, rather than typing in this same code repeatedly throughout the program.
Since you want to be able to simulate dice with different numbers of sides, a good name for the value
to use would be ‘sides’. Python uses the statement def to name a function.
def roll_dice(sides):
The function code is then written indented beneath the defstatement. Within this code, the variable
that is used to return the random number to the main program must be specified. In this case, it has
been named 'number'. Python uses return to bring the result of the calculation back to the main
program.
import random def roll_dice(sides):
number = random.randint(1,sides) return(number)
sides = int(input("How many sides does the dice have?"))
throw = roll_dice(sides) print(throw)
To call a function in Python, simply use its name (include the brackets) and the value it needs to use
for calculation, plus a variable that the returned value will be stored in – in this case, 'throw'.
throw = rolldice(sides)
GCSE Functions, procedures and modules
Functions and procedures summarise sets of programming instructions. Modules are used to group
functions and procedures for a specific purpose.
In the same way that a textbook is divided into chapters, a program is divided into related
functionality using modules.
Programs usually integrate blocks of code and modules that have already been created in other
projects.
The algorithms a program uses are implemented as the functions and procedures in these modules.
Algorithms can be broken down into procedures or functions. This saves time by only having to
execute (call) the function when it is required, instead of having to type out the whole instruction set.
Programming languages have a set of pre-defined (also known as built-in) functions and procedures.
If the programmer makes their own ones, they are custom-made or user-defined.
Procedures or functions?
A procedure performs a task, whereas a function produces information.
Functions differ from procedures in that functions return values, unlike procedures which do not.
However, parameters can be passed to both procedures and functions.
In a program for drawing shapes, the program could ask the user what shape to draw. The
instructions for drawing a square could be captured in a procedure. The algorithm for this action
could be a set of tasks, such as these:
Repeat the next two steps four times:
Draw a line of length n.
Turn right by 90 degrees.
If this were a computer program, this set of instructions could be given the name 'square' and this
sequence would be executed by running (calling) that procedure.
A function could calculate the VAT due on goods sold. The algorithm for this function could be:
VAT equals (value_of_goods_sold * 0.2)
Return VAT
If this were a computer program, this set of instructions could be given the name 'calculate_VAT' and
would be executed by running (calling) that function.
The function would then return the value as VAT which is then used elsewhere.
Modules
Computer programs are often divided up into smaller sections called modules. A module collects
together related functionality – such as functions, procedures and other information.
Computer program needs a way of referring to modules, so they are given names. This allows you to
say something like:
or
There are many modules available in programming languages to perform everything from graphics
to complicated mathematics. Many of these are included by default with a programming language.
You can also install new ones or you can make your own.
If you chose to make a dice simulation game using Python, you would want a part of the program to
be able to choose a random number in the range of 1 to 6.
Helpfully, a 'random' module already exists for Python. Someone has already created a program
(random.py) which contains the instructions that are needed to generate a random number. This
module is saved in a directory on your computer that the Python interpreter is able to access.
"find the module called random, and find out what functions it has".
"use the function randint from the module random with a lower number of 1 and an upper number
of 6".
Custom modules
Modules can be customised by a programmer to do a particular task in a program.
This example of Python code shows how pre-existing procedures and modules can be combined and
modified to make a custom-made procedure.
If you wanted to have the option of rolling a dice with a different number of sides, you could make
these changes:
import random def rolldice(sides): number=random.randint(1,sides) print (number)
Then call the procedure rolldice(12). The word "sides" is known as a parameter. The number 12 in the
brackets is known as the argument.
If you were to save this program as 'rolldice.py', you could import it into other Python programs
where you needed to choose a random number in a range. For example:
import rolldice rolldice.rolldice(12)
Parameters
Parameters allow us to pass information or instructions into functions and procedures. They are
useful for numerical information such as stating the size of an object.
Parameters are the names of the information that we want to use in a function or procedure.
The values passed in are called arguments.
For instance, we can create a procedure that draws a square - but for it to be useful we need to also be
able to specify how large it should be.
The following example creates a procedure called 'square'. In the line where we define the name for
this procedure, we have included a variable called 'distance' inside the brackets. Distance is
a parameter - it allows us to pass a value into the procedure for it to use.
Once this code has been written, a procedure called 'square' has been created. Running the following
code would create a square of size 50 for each side:
square(50)
You can add more parameters to a function or procedure by separating the variable names with
commas. For example:
def square (distance, colour):
Scope
Scope refers to where a function, procedure, variable or constant can be used. They can be local or
global.
A global variable is declared in a way that makes it available to every other part of the program,
whereas a local variable is declared in a way that makes it only available within a specific function.
For example, this program asks for a name, and then prints that name out three times.
name = input("Please enter your name") def greet(): for x in range (0, 3): print (x, name) greet()
Note that:
name is a variable that is global in its scope
Identifiers
Programming languages have many parts. These may
include functions, procedures, methods, parameters, arguments, fields, data
types, classes, modules, units, constants, and variables.
Each part is given a name, called an identifier. Every part must have a unique identifier.
If a programmer wants to create functions, procedures or any other program part, each one must also
be given different identifiers.
Creating identifiers
By using different names. For example, it is quite clear that the names 'Katie' and 'Aisha' are different.
By using the scope rules of the language. These are rules that define whereabouts in a program each
identifier has a meaning. The scope of an identifier refers to the sections of the source code where its
meaning is defined. Elsewhere in the source code it is undefined.
Identifiers may have global scope - in which case they have meaning throughout the whole of the
program and that meaning is the same everywhere. Or, identifiers may have local scope - in which
case they have meaning only within a small part of the program, and they may be defined as having
different meanings in different places.
Identifiers may also have module scope - in which case they have meaning throughout a single
module or file.
This allows us to use the same name in different places to refer to different things. These names are
actually different identifiers, even though a casual reader might think they are the same.
We can safely divide programming projects into smaller components, because programmers writing
one component may choose names that are local to that component without worrying what names
have been chosen by programmers writing other components.