- Home
- Lessons
- GCSE & IGCSE Computer Science
- Subprograms: functions and procedures
Subprograms: functions and procedures
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
Subprograms are named blocks of code you can call whenever you need them. They are how big programs stay organised.
Functions and procedures
A function returns a value with return.
def area(width, height):
return width * height
print(area(4, 5))
A procedure carries out a task but does not return a value.
def greet(name):
print("Hello", name)
greet("Kai")
Parameters are the names in the brackets (width, height). The values passed in when it is called (4, 5) are the arguments.
def area(width, height):
return width * height
print(area(4, 5))
A procedure carries out a task but does not return a value.
def greet(name):
print("Hello", name)
greet("Kai")
Parameters are the names in the brackets (width, height). The values passed in when it is called (4, 5) are the arguments.
Built-in and library subprograms
Python has built-in subprograms such as print(), len(), int() and input().
Library subprograms are imported, for example:
import random
dice = random.randint(1, 6) gives a whole number from 1 to 6 inclusive.
Library subprograms are imported, for example:
import random
dice = random.randint(1, 6) gives a whole number from 1 to 6 inclusive.
Local and global variables
A local variable is created inside a subprogram and only exists while it runs.
A global variable is created in the main program and can be read anywhere.
Using local variables avoids one part of a program accidentally changing another.
Benefits of subprograms: code is reused instead of repeated, each part can be tested on its own, programs are easier to read, and work can be shared in a team.
A global variable is created in the main program and can be read anywhere.
Using local variables avoids one part of a program accidentally changing another.
Benefits of subprograms: code is reused instead of repeated, each part can be tested on its own, programs are easier to read, and work can be shared in a team.
What does this print?
x = 10
def change():
x = 5
return x
y = change()
print(x + y)
- x = 5 inside change() is a new local variable.
- The global x is still 10, and y = 5.
- 10 + 5
Answer: 15
Functions return values; procedures do not. Parameters receive values passed in. Local variables exist only inside the subprogram. Subprograms make code reusable, testable and readable.
Check you have got it
Answer 7 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.