PROCEDURES
AND
FUNCTIONS
FUNCTIONS AND
PROCEDURES
In today’s lesson we will look at:
• what functions and procedures are
• the difference between the two
• when we might want to use one
• creating functions and procedures in
Python
FUNCTIONS AND PROCEDURES
• Functions and procedures are small sections of code used to
perform a specific task.
• They are used for three reasons:
• they can be used to avoid repetition of commands within the
program
• careful use of functions and procedures helps to define a logical
structure for your program by breaking it down into a number of
smaller modules
• you can re-use the same code to do the same job in another
program
• Both functions and procedures are defined at the top of your
FUNCTIONS AND PROCEDURES
Are functions and procedures the
same?
• procedures does not return a value
• functions return a value – e.g.
they calculate an answer and send
it back
• However, in some programming languages
there are only functions, and procedures are
WHEN ARE FUNCTIONS USEFUL?
• Python has functions and procedures built in – e.g.
print() doesn't return a value, but len() does.
• You’ve probably used a function in a spreadsheet – e.g.
=sum() returns the total value of the numbers in the
range. We don’t need to write all of the code to do that.
• Blocks in Scratch are procedures – remember how they
were used to simplify the Simple Spirograph program?
PROCEDURES IN PYTHON
• Procedures in Python are really the same,
except that they don’t return a value.
• For example
Function
def hello():
Definition Note that
print("Hello World") there is
no
return
value –
hello() the
procedure
Function Call just
FUNCTIONS IN PYTHON
• Functions are called using their name,
e.g.
Parameter
Function def double(x):
Definition
return x*2
Argument
print(double(3))
Function Call
PARAMETERS AND ARGUMENTS
Parameters in
function
definition
Arguments in
function call
PROCEDURES WITHOUT PARAMETERS
Procedures without parameters are known as void
functions in python
1 EXAMPLES
2
def stars( ) :
print(“* * * * * “)
stars( )
PROCEDURES WITH PARAMETERS
EXAMPLES
2
PROCEDURES WITH
PARAMETERS
3
EXAMPLES
FUNCTIONS
Functions are names as fruitful functions in
python
Celsius to Fahrenheit
Fahrenheit to Celsius
print(Celsius(43))
FUNCTION EXAMPLE
BE CAREFUL WITH VARIABLES!
• You can create and use variables inside a function or
procedure, but these are called local variables
• Local variables:
• can’t be accessed by any other part of the program
• have their values reset each time the function or
procedure is called
• Python assumes that all variables in a function or
procedure are local – to change a global variable you need
to "declare" it at the top of that function or procedure, e.g.
global score
Task –
Practice and execute all
python examples