A Subroutine is a small self-contained section of code that completes a task or process. If you think about the theory of modular programming where you end up with small solvable problems – these are the sub-routines that together make up the program.
There are a number of advantages of using sub routines:
- You can reuse your code :- in a game a player will take many turns and therefore it makes sense to have a sub-routine that deals with player-turns( ). Likewise you’d need to check if someone has won many times and therefore a iswinner( ) subroutine would be useful. Notice that subroutines are written with normal brackets following them.
- It makes your program easier to maintain:- If you only have one place in your program where you write to a file and that process needs to change you only have to maintain one section of code.
- If you need a hashtable routine and have already written one it’s very easy to cut and paste the routine from one program to another.
Earlier we said that subroutines are written with trailing brackets. This is so we can pass values to the subroutines, these inputs are known as parameters or variables e.g.
getSquareArea( sidea, sideb) When is comes to returning values there are two types of Sub Routine (Procedures and Functions). Procedures don’t return values they just do something. Functions (like Maths ones) do return values using the return keyword. In Python, like many modern languages, we don’t differentiate between procedures and functions we just have functions. To create a function we use the def keyword e.g.
def getSquare( sidea, sideb):
return sidea * sideb
One of the frequent questions regards to returning values from routines is how to return more than one value. Python has a very useful feature that allows us to create a tuple (type of array) on the fly e.g.
def getSquareData ( sidea, sideb):
perimeter = sidea + sideb + sidea + sideb
area = sidea * sideb
return [ perimeter , area ]
Note: return perimeter, area and return (perimeter,area) would also work. Last snippet :- Python allows you to define default values for your routines so you could declare our getSquare routine as:
def getSquare ( sidea = 0, sideb = 0)