Y11-13-02-2024-8.1 Procedures and Functions
Y11-13-02-2024-8.1 Procedures and Functions
Science
With: Mr Mike
Procedures and functions
Date: 13 February 2024
When writing an algorithm, there are often similar tasks to perform that make
use of the same groups of statements.
Instead of repeating these statements and writing new code every time they are
required, many programming languages make use of subroutines, also known as
named procedures or functions.
These are defined once and can be called many times within a program.
Procedures, functions and parameters
Parameters are the variables that store the values of the arguments passed to
a procedure or function. Some but not all procedures and functions will have
parameters.
Definition and use of procedures and functions, with or
without
parameters
Procedures without parameters
Here is an example of a procedure without parameters in pseudocode:
The procedure can then be called in the main part of the program as many times
as is required in the following way:
Definition and use of procedures and functions, with or
without
parameters
Instead of calling them procedures, different terminology is used by each
programming language. Procedures are known as:
» void functions in Python
def Stars():
print("************")
Stars()
It is often useful to pass a value to a procedure that can be used to modify the
action(s) taken. For example, to decide how many stars would be output. This is done
by passing an argument when the procedure is called to be used as a parameter by
the procedure.
Procedures with parameters
Procedure with parameters are called like this – in this case to print seven stars:
Procedure stars with parameter – definition
def Stars(Number):
for counter in range (Number):
print("*", end = "")
Stars(7)
A procedure call must match the procedure definition. This means that when a
procedure is defined with parameters, the arguments in the procedure call should
match the parameters in the procedure definition.
Functions
Just like a procedure it is defined once and can be called many times within a
program.
Unlike procedures, function calls are not standalone and instead can be made on
the right-hand side of an expression.
Functions
Because a function returns a value, it can be called by assigning the return value
directly into a variable as follows:
def Celsius(Temperature):
return (Temperature - 32) / 1.8
Python – data type of function does not need to be defined
Activity 8.16
Go to todays lesson, use replit to write your program, post a screenshot of your code
and the output after you run your program, turn your work in at the end of the lesson
Pop Quiz
1. What is a function?
» A block of code that can be called many times
2. What is the difference between a procedure and a function?
4. What is a subroutine?
» Procedure
» Function
Thank you.