Programming · Functions & Procedures
up to +100 XP
Stop 2.7 · Programming · 3 min

Functions & Procedures

Learn to organize code into reusable blocks

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.

FunctionProcedure
ParametersMay or may not take parametersMay or may not take parameters
Returns a resultMust return a resultMust not return a result
Examplearea(width, height) returns a numbershow_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

import math, random
print(math.sqrt(16))           # 4.0
print(random.randint(1, 6))    # a dice roll

Pre-written code

BenefitsDrawbacks
Saves development timeYou may not know exactly how it works
Usually well tested and reliableThird-party code may contain bugs or security flaws
Lets you do complex tasks (maths, graphs) easilyIt may stop being supported or change in an update
Consistent and widely understoodLicences may restrict how you use it

Debugging functions and procedures

Quick check · 11 questions · up to 100 XP

Check what stuck.

+10 XP each
Question 1

Question 1 of 11

What must a function do that a procedure must not?

Question 2

Question 2 of 11

Can a procedure take parameters?

Question 3

Question 3 of 11

Which is a pre-written, built-in Python function?

Question 4

Question 4 of 11

Where does random.randint() come from?

Question 5

Question 5 of 11

Which is an example of a third-party library?

Question 6

Question 6 of 11

What is a benefit of using pre-written code?

Question 7

Question 7 of 11

What is a drawback of third-party pre-written code?

Question 8

Question 8 of 11

In def area(width, height):, what are width and height?

Question 9

Question 9 of 11

A function has no return statement. What does calling it give?

Question 10

Question 10 of 11 · Match the pairs

Match each term to its meaning.

Function
Procedure
Parameter
Argument
Question 11

Question 11 of 11 · Coding

Write area(width, height) that returns the area of a rectangle.

Open the IDE
Hint

Multiply width by height and return it.