What is a subroutine?
Subroutines are self-contained sections of code that can be called and run independently. They may or may not accept parameters which are values passed in from
the main program. There are two key types of subroutines:
- Procedures
- Functions
To work correctly with
subroutines, they should only use local variables that are passed into the subroutine as parameters and not global variables.
Procedures
Procedures are a type of subroutine that does not return a value. They may take parameters i.e. values that are passed into the subroutine to use but they do not
return any values to the main program when they are run.
Defining a procedure
A procedure is made up of the def command and an identifier followed by brackets that may or not contain parameters. Then the code to be executed when the procedure
is called.
Example 1
def add_two_nums(num1, num2): total = num1 + num2 print(f"{num1} + {num2} = {total}") |
Example 2
def signature(): print(“A.Name”) print(“CEO Company ABC”) print(a.name@abc.co) |
procedure defining syntax rules:
- Def is in lower case at the start of the procedure
- A suitable identifier has been selected
- There are brackets that may or may not contain parameters to be passed in
- There is a colon on the end of the def line
- All the code to be executed when the subroutine
is called is indented under the def line
The first code subroutine add_two_nums takes two parameters num1 and num2. This means it needs to be given two arguments when we call it. The second procedure does not take parameters.
We must still pass empty brackets when we call it.
Calling a procedure
To call a procedure means to run it. We can call a procedure by using it's identifier and passing any necessary arguments. When we pass an actual value for one of
our parameters defined in the subroutine we call it an argument. If a procedure does not take any parameters you still need to add opening and closing brackets after
the identifier to call it. The above procedures would be called as follows.
add_two_nums(3,4) signature() |
The first would output '3 + 4 = 7' and the second would print the three lines of the signature one underneath each other. If you tried to call a procedure but pass the wrong number of
arguments then you will get an error.
Syntax checker
Fix the code below so the subroutine takes two integer inputs and outputs whether the first is a multipe of the second e.g. if the user enters 18 and then 3 the output will be 'This is a multiple'.
def isMult(num1,num2): # colon added |
if num1 % num2 == 0: # equals to double equals and correct var names |
print("This is a multiple") # indentation corrected |
else: # no condition for else |
print("This is not a multiple") # indentation corrected |
isMult(18,3) # removed from print statement |