1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 6. Subroutines


Lesson Objective

  • Understand the purpose of subroutines and be able to explain what parameters, functions and procedures are.
  • Maybe understand the meaning of scope too.

Lesson Notes

Subroutine?

Pre written code that can be called throughout a program to perform a specific task. There are two types of subroutines, Functions and Procedures. A Function returns a value and a Procedure just executes commands. You can pass data, known as parameters, into a subroutines.


Procedures

Subroutines are defined using the ‘def’ keyword. To call a subroutine, use the subroutine name followed by parenthesis.

Code:

def myProcedure():
   print(“Hello, welcome to my procedure”)

myProcedure()
mrProcedure()

Cmd Output:

Hello, welcome to my procedure
Hello, welcome to my procedure 

Functions

Information can be passed to functions as parameter. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

To let a function return a value, use the return statement.

Code:

def myFunction(x):
   print (5 * x)
   return 5 * x

myFunction(5)
myFunction(10)
myFunction(2)

Cmd Output:

25
50
10

Functions Vs. Procedures

The function will store the data that has been “returned”. It can be used in calculations and other processes.

Code:

def myProcedure(a):
   z = 10 + a

def myFunction(a):
   z = 10 + a
   return z

num = input(“Enter a number: ”)
print(myProcedure(num))
print(myFunction(num))

Cmd Output:

Enter a number: 4
None
14

Advantages of Subroutines


Scope

Scope refers to where in a program a variable or constant can be used. They can be local or global.

A variable that is given global scope is referred to as a global variable. It is a variable that can be accessed and used anywhere is a program.

A variable that is given local scope is referred to as a local variable. It is a variable that can only be used within a specific subroutine.

In the example below, the “name” variable is global. It can be used everywhere in the program code. The “i” variable can only be used in the for Loops (Lines 4 to 6).

Code:

1.  name = input(“Enter your name: ”)
2.  
3.  def greetings():
4.    for i in range (5):
5.      print (i) 
6.      print (“Hi ” + name)
7. 
8.  greetings()
9.  print (“Byeee ” + name)

Cmd Output:

?

3