Procedures & functions
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A function is a named block
- A function is a named block of code you can run again and again.
- Define it once with
def, then call it by name. - This avoids repeating yourself and keeps programs tidy.
def greet():
print("Hello!")
greet()
greet()
Parameters pass data in
- A parameter is a value the function receives.
- Put it in the brackets, and pass an argument when you call.
- IGCSE allows up to three parameters.
def greet(name):
print("Hello, " + name)
greet("Ada")
greet("Sam")
Functions return a value
- A function hands a value back with
return. - A block that only does something and returns nothing is a procedure.
def square(n):
return n * n
answer = square(6)
print(answer) # 36
Explore
Call and return
Calling runs the function's body; return hands a value back.
In the exam: PROCEDURE and FUNCTION
- Pseudocode separates a
PROCEDURE(no result) from aFUNCTION(returns a value).
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION
Common mistakes
- A function returns a value with
return; a procedure just does a job. - Call it with
(). - Parameters receive the arguments in order.
Now you try
- Write each function — it is then called for you in the check.
- Press Check answer to test your code.
Write a function double(n) that returns n times 2.
Click Run to see the output here.
Write a function is_even(n) that returns True when n is even, otherwise False.
Click Run to see the output here.
Write a procedure print_stars(n) that prints a line of n star (*) characters, then call it with 4 so it prints ****.
Click Run to see the output here.