Programming constructs - CCEAFunctions and procedures

Computer programs use data stores to organise the different types of data they contain. Data stores can be either a constant, variable or an array, and contain inputs, outputs, functions, instructions, sequences and more.

Part ofDigital Technology (CCEA)Digital development concepts (programming)

Functions and procedures

When you have a of instructions you will use at different stages in a computer program, it is often helpful to place the instructions in a sub-program or .

The subroutine can then be called at the relevant points in the program. and are both subroutines.

Procedures

A procedure is a way of giving a sequence of instructions a named identifier which can then be called from anywhere in the program. Procedures can also take inputs – these are known as .

To make a procedure that welcomes the user to a program we would write the following code:

def hello(name): print("Hello " + name + " nice to meet you") hello("Alice")
hello("Bob")
hello("Sue")

Will output:

Hello Alice nice to meet you
Hello Bob nice to meet you
Hello Sue nice to meet you

We can create procedures to help us reuse code and make maintenance easier – errors only have to be fixed in the procedure once.

The set of instructions has been given the identifier 'hello' and takes one – 'name'. The procedure has been called three times in the program.

Functions

A function is a subroutine that returns a value. This means that it outputs a value from the instructions it carries out. Like a procedure, a function groups together a number of instructions under one name.

We can make a function that creates a username based on the following rules: initial of forename, surname and the last two digits of their year of birth.

For example, to create a username for Joe Bloggs, we would write the following code:

def userName(fname, sname, year): uname = str(fname[0] + sname + year[-2:]) return uname
forename = "Joe"
surname = "Bloggs"
yearOfBirth = "2001" username1 = userName(forename, surname, yearOfBirth)
print(username1)

The above function uses string manipulation to strip the first letter from the forename, then concatenates this with the surname and the last two digits of the variable 'yearOfBirth'.

The code will output:

JBloggs01

The benefit of this code is that it can be reused to create usernames for all users, by simply calling the function when required.

When a function returns a value it must be returned to a , such as a variable, or an array. As functions return values, they can be used to execute more complex tasks.