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.
KS3, GCSE, A-Level Computing Resources
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.
Subroutines are defined using the ‘def’ keyword. To call a subroutine, use the subroutine name followed by parenthesis.
def myProcedure(): print(“Hello, welcome to my procedure”) myProcedure() mrProcedure()
Hello, welcome to my procedure Hello, welcome to my procedure
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.
def myFunction(x): print (5 * x) return 5 * x myFunction(5) myFunction(10) myFunction(2)
25 50 10
The function will store the data that has been “returned”. It can be used in calculations and other processes.
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))
Enter a number: 4 None 14
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).
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)
?