Functions
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Name a block of code
- A function is named code you can use again and again.
- Make one with
def name():and an indented body. - "Calling" the function by its name runs that code.
Give it inputs (parameters)
- The names in the brackets are parameters — the function's inputs.
- When you call it, you pass in arguments (the real values).
- A function can take more than one parameter.
def shout(word):
print(word.upper() + "!")
shout("hello")
Send back a result (return)
returnsends a value back to whoever called the function.- You can store that value or use it in an expression.
returnalso ends the function straight away.
def double(x):
return x * 2
result = double(5)
print(result)
return vs print
printonly shows something on the screen.returngives a value back that the rest of your code can use.- A function with no
returngives backNone.
In Cambridge pseudocode
- A
FUNCTIONreturns a value; aPROCEDUREjust does an action.
FUNCTION Add(a : INTEGER, b : INTEGER) RETURNS INTEGER
RETURN a + b
ENDFUNCTION
PROCEDURE Greet(name : STRING)
OUTPUT "Hello, ", name
ENDPROCEDURE
Now you try
- Define each function, then the checks will call it for you.
- Use
returnto send the answer back (do notprintit).
Write a function add(a, b) that returns the sum of a and b.
Click Run to see the output here.
Write a function greet(name) that returns the string Hello, then the name then !. So greet("Sam") returns Hello, Sam!.
Click Run to see the output here.
Write a function biggest(a, b) that returns the larger of the two values. If they are equal, return either one.
Click Run to see the output here.