Python For GCSE
A subroutine is a named block of code that can be executed (called) as many times as you like in a program. Subroutines combine multiple lines of code into a block that can be called with a single line. This makes programs,
- More efficient
- Easier to write
- Easier to read, understand and debug
As far as the GCSE examination is concerned, subprograms and subroutines are the same things.
Here is an example of a procedure,
def square(n): sq = n * n print(n, "squared is", sq) square(4) square(10)
This code defines a new statement for us. The statement is called square.
When we write the statement (call our subroutine), we also have to supply the number that we want to square. In this definition, the letter n is written brackets. It is called a parameter for the subroutine. Subroutines can have 0 or more parameters. These are values that need to be supplied when the procedure is called. The letter n, in this definition, is the variable that stores the number that the programmer wants to square.
When we call the procedure, the value we supply for this parameter is called an argument. When we have defined a subroutine, we are able to reuse it over and over again. When using subroutines, place your subroutine definitions at the top of a program, then write the main program underneath.