Procedures

Procedures

As mentioned before, a procedure is a subroutine that just executes commands. It runs separately to the main program and does not transfer any data back. For example, if you perform a calculation in the main program you cannot work with those same values over in the procedure, and the other way round.

A subroutine, whether it is a procedure or a function, needs to be defined at the start of the program, before it is called within the main program. To define a subroutine we start with the word def (which stands for define) and then write the subroutine name, closed brackets (which are the parameters – but in a procedure these are empty) and a colon (remember this stands for ‘then’). For example:

subroutines3

You must remember to indent everything that you want contained within the subroutine, beneath it (just like an if, for or while statement). For example, a procedure for printing a song chorus is written out below:

subroutines4

Now that you have defined your subroutine you need to call it in the main program. You do this by writing the name of the subroutine and then the parameters in brackets (parameters are any variables or data that you wish to send over to the subroutine – but procedures don’t use or return data so the brackets will be left blank). You can call a subroutine as many times as you like in a program. To call a procedure in the main program:

subroutines17

An example of a procedure, in the form of a song, is shown below:

subroutines5

This would output the following:

subroutines7

It is a good idea to use comments in your code, this is so that you can identify to yourself or others who read it, what certain sections are doing. To insert a comment use the # symbol. Comments are not displayed when the program is run. Adding comments to the previous program would make it clearer to spot what it happening:

subroutines6

Practice Task 1

Subroutines not working? Tick off these common errors:

  • Make sure that you define your subroutine at the start of your program.
  • You need to write def then the name of the subroutine then any parameters in brackets and then a colon. For example: def Calculation(x,y):
  • You need an indent beneath a subroutine for each line within the subroutine (just like an if statement or loop). Un-indent it back over when you have finished.

    < Back to Section Seven