Subroutines
Coding: Introduction to Python v3, topic 3.1.1
Subroutines
A subroutine is a named block of code within your program.

Advantages of subroutines
- Easier to read:
- There are fewer long blocks of code to understand.
- More efficient:
- Blocks of code can be written once and reused many times.
- More reliable:
- Each subroutine can be individually tested to ensure it works.

Parameters and arguments
- Parameters are special variables used to pass values into a subroutine.
- Arguments are the actual values that are passed in.

Types of subroutine
- A function is a subroutine which returns a value.
- A procedure is a subroutine which does not return a value.
Scope
The scope of a variable is the group of areas of the code from which it can be accessed.

Local scope
- A variable defined within a subroutine will have local scope.
- This means that they can only be accessed within that subroutine.

Global scope
- A variable can be made global by adding the 'global' keyword in front of it when it is first used.
- Global variables may be accessed by any part of the whole program.
What Should be in a Subroutine?
Subroutines are key to maintainable code, but must be used correctly.

Good ideas for subroutines
- Subroutines should include single processes only.
- Subroutines should ideally be designed so that they can be reused in multiple parts of code, both within and outside of your program.
- Good examples of subroutines include:
- Calculating the sum of a list.
- Finding a largest element of a list.
- Opening a specific part of an application.

Bad ideas for subroutines
- Subroutines should not be used for very long processes
- Subroutines should be split into multiple subroutines so that they don’t often exceed about 30 lines of code.
- Bad examples of subroutines include:
- The whole application.
- A very specific, and non-reusable piece of code.
Test yourself on Subroutines
In the following code, is x a parameter or an argument?
def name(x, y):
return x + yWhat is an argument of a subroutine?
What is global scope?
Which of the following are good examples of subroutines?