Procedures and abstraction
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
What we'll do
- A procedure is a named block of code you can use again and again.
- In Python a procedure is made with
def. - This is part of Big Idea 3: building programs from reusable parts.
Make a procedure
- Start with
def, then a name, then(). - Put the code indented below.
- Call the procedure by writing its name with
().
def greet():
print("Hello!")
greet()
greet()
Parameters pass data in
- A parameter is a value the procedure receives.
- Put the parameter name inside the
(). - Inside the procedure you use it like a variable.
def greet(name):
print("Hello, " + name)
greet("Mia")
greet("Sam")
return gives a value back
returnsends a value out of the procedure.- The caller can store that value or use it.
- After
return, the procedure stops.
def square(n):
return n * n
answer = square(5)
print(answer)
Why procedures help: abstraction
- Abstraction means hiding the details behind a simple name.
- You call
square(5)and do not think about how it works inside. - This makes code shorter, clearer, and easy to reuse.
In AP CSP pseudocode
- The exam uses a pseudocode for procedures.
PROCEDUREis likedef;RETURNis likereturn.
PROCEDURE square(n)
{
RETURN(n * n)
}
Now you try
- Read each task to see the procedure name and what it must return.
- Press Check answer to test your code.
Write a procedure square(n) that returns n multiplied by itself. Do not print inside it — use return.
Click Run to see the output here.
Write a procedure area(width, height) with two parameters that returns the area (width times height).
Click Run to see the output here.
Write to_seconds(minutes, seconds) that returns the total number of seconds. (One minute is 60 seconds.) Then it combines a multiply step and an add step.
Click Run to see the output here.
The procedure double(x) is given. Call it with 21 and store the result in a variable named result.
Click Run to see the output here.