0% found this document useful (0 votes)
35 views

Procedures and Functions

Procedures and functions help keep programs simple and short by breaking code into smaller, reusable sections. Procedures perform specific tasks without returning a value, while functions perform calculations and return a value. Modules group related functions and procedures to organize program functionality into logical blocks.

Uploaded by

Mohammed Seedat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Procedures and Functions

Procedures and functions help keep programs simple and short by breaking code into smaller, reusable sections. Procedures perform specific tasks without returning a value, while functions perform calculations and return a value. Modules group related functions and procedures to organize program functionality into logical blocks.

Uploaded by

Mohammed Seedat
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

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.

Why use procedures?


Program code is easier to read and understand when it is broken up into smaller sections. By breaking
a program up into these sections, or procedures, code can be made shorter and simpler.

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.

Procedures can make code shorter, simpler and easier to write.

Writing a procedure is extremely simple. Every procedure needs:

 a name
 the program code to perform the task

Python uses the statement def to name a procedure. 

The procedure code is then written indented beneath the def statement

Indented code tells Python that the code belongs to the procedure.

Running a procedure in Python


Once a procedure is named and written, it can be called at any point in the program.

’Calling’ a procedure means running it.

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)

# End of level update_display()


# Lose a life update_display()
# New high score update_display()
# Game over update_display()

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

Why do we use functions?


Program code is easier to read and understand when it is broken up into smaller sections. Functions
and procedures can make code shorter, simpler and easier to write.

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

 the values that it needs to use for calculation

 the program code to perform the task

 a value to return to the main program

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.

Writing a function in Python


To create a function, first give the function a name, and name the value that the function should use
in its calculations. A good name for the dice-rolling function could be ‘roll_dice’.

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)

Running a function in Python


Once a function is named and written, it can be called at any point in the program.

’Calling’ a function means running it.

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.

What are functions and procedures for?


Computer programs can consist of thousands of lines of code, just like a textbook can have thousands
of words.

In the same way that a textbook is divided into chapters, a program is divided into related
functionality using modules.

In a textbook, specific concepts are covered on a section-by-section or paragraph-by-paragraph basis.


Similarly, in a computer program, specific functionality is divided up into named functions and
procedures.

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.

Using functions and procedures


In a computer program there are often sections of the program that we want to re-use or repeat.
Chunks of instructions can be given a name - they are called functions and procedures.

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.

In our example, the function would be called by using:


calculate_VAT(value_of_goods_sold)

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:

"call the function get_shape_to_draw from the module user_interface"

or

"call the procedure draw_square in the module shape_drawing".

The modules you write form your program.

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.

Modules can be changed or modified without affecting the overall program.

Using modules - an example

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.

The script would look something like this:


import random number = random.randint(1,6) print ("The dice rolled a ",str(number))

Adding the line import random to the program tells the computer:

"find the module called random, and find out what functions it has".

The program can then say:

"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.

In the following code, a procedure 'rolldice' is created to emulate a dice roll:


import random def rolldice(): number=random.randint(1,6) print (number)

To roll the dice, you would need to call the functions by typing:


rolldice()

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. 

The pseudocode is included as a comment after the #.


import turtle #import the turtle graphics module window = turtle.Screen() # make a graphics window called
"window" fred = turtle.Turtle() #make a turtle called "fred" def square (distance): for x in range (0,4):
fred.forward(distance) fred.right(90)

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)

The 50 here is called the argument - because it is a value passed in.

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.

A module-scoped variable is only available with a single file or module.

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

the x variable in the loop for x in range... is local to the greet function. If you tried to access x from


outside this function, you would get an error message as it only exists inside greet

if the same code above was in a module file, then name would be module-scoped

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

Identifiers are made unique in two ways:

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.

You might also like