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.

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.

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:

See this example

screenshot_1202.jpg - 4/2016

About CDB 360 Articles
Self-Employed Software Developer, Spark, Property Management, Hobby Forestry, Ex-Teacher, Engineering - Wood, Metal, Electrics & Computers. Outdoors - Walk, Cycle, Kitesurf,

Be the first to comment

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.