Functions and procedures
When you have a sequenceA sequence is a set of numbers that follow a certain rule. 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 subroutinePortion of code that may be called to execute anywhere in a program..
The subroutine can then be called at the relevant points in the program. functionA group of instructions, also known as a procedure and procedureA set of code instructions that tell a computer how to run a program 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 argumentThe values of pieces of data or parameters provided as input into a function..
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 youWe 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 argumentThe values of pieces of data or parameters provided as input into a function. – '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:
JBloggs01The 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 data storeA data store is a location for keeping and managing collections of data including databases and simpler types such as files and emails, such as a variable, tuplea finite list of data, equivalent to a record or row in a database. or an array. As functions return values, they can be used to execute more complex tasks.