- Home
- Lessons
- KS3 Computing
- Python: procedures and functions
Python: procedures and functions
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
Big programs are built from small, named blocks of code called subprograms. Write a block once, then use it as often as you like.
Defining a subprogram
Use def, a name, brackets and a colon. The indented lines are the body.
def greet(name):
print("Hi " + name)
greet("Zara")
Output: Hi Zara
name is a parameter: a value passed in when the subprogram is called. "Zara" is the argument.
def greet(name):
print("Hi " + name)
greet("Zara")
Output: Hi Zara
name is a parameter: a value passed in when the subprogram is called. "Zara" is the argument.
Procedures and functions
A procedure carries out a task but does not send a value back (greet above just prints).
A function sends a value back with return.
def area(width, height):
return width * height
print(area(4, 5))
Output: 20
A function sends a value back with return.
def area(width, height):
return width * height
print(area(4, 5))
Output: 20
Why use subprograms?
Reuse: write the code once, call it many times.
Decomposition: each subprogram solves one small part of the problem.
Testing: you can test each part on its own.
Teamwork: different people can write different subprograms.
Programs built this way are called modular.
Decomposition: each subprogram solves one small part of the problem.
Testing: you can test each part on its own.
Teamwork: different people can write different subprograms.
Programs built this way are called modular.
What does this print?
def double(n):
return n * 2
x = double(3)
print(double(x))
- double(3) returns 6, so x = 6.
- double(6) returns 12.
Answer: 12
Define subprograms with def. Parameters receive values. A function returns a value; a procedure does not. Subprograms make code reusable, easier to test and easier to share in a team.
Check you have got it
Answer 6 quick questions with instant marking. If you get one wrong, GCSE-ready shows you why and gives you another go. It is free, and you do not need an account.