Learning objectives:
- Know the characteristics of functions and procedures (2.7.1–2.7.2)
- Know where functions and procedures come from (2.7.3)
- Know the benefits and drawbacks of pre-written code (2.7.4)
- Interpret, develop and debug user-written and pre-written code (2.7.5–2.7.7)
Functions and procedures
Both are named blocks of code that do one job and can be called (used) as many times as needed.
| Function | Procedure | |
|---|---|---|
| Parameters | May or may not take parameters | May or may not take parameters |
| Returns a result | Must return a result | Must not return a result |
| Example | area(width, height) returns a number | show_menu() prints a menu |
def area(width, height): # function: returns a value
return width * height
def show_receipt(item, cost): # procedure: does a task, returns nothing
print(item, "costs £" + str(cost))
room = area(4, 3)
show_receipt("Carpet", room * 12)
Parameters are the names in the definition (width, height). Arguments are the values passed in when it is called (4, 3).
Where functions and procedures come from
- User-written: you write them with
def. - Pre-written and built-in: part of Python, such as
print(),len(),round(),max(),min(),range(). - Pre-written in libraries that come with the language: imported first, such as
math.sqrt()orrandom.randint(). - Pre-written in third-party libraries: installed separately, such as pandas or Matplotlib.
import math, random
print(math.sqrt(16)) # 4.0
print(random.randint(1, 6)) # a dice roll
Pre-written code
| Benefits | Drawbacks |
|---|---|
| Saves development time | You may not know exactly how it works |
| Usually well tested and reliable | Third-party code may contain bugs or security flaws |
| Lets you do complex tasks (maths, graphs) easily | It may stop being supported or change in an update |
| Consistent and widely understood | Licences may restrict how you use it |
Debugging functions and procedures
- Calling with the wrong number or order of arguments.
- Forgetting
return, so a function givesNone. - Using a variable that only exists inside another function (scope).
- Forgetting to
importa library function before using it.