Saturday, 7 October 2017

Homemade (User Defined) Functions

Functions can be described as a discrete set of instructions that perform a task and can be called using the function name. Think of them as miniature programs within a program. In QBasic they are known as subroutines.
I have already mentioned a number of functions:
  • There are built-in functions that are always available in Python, such as print(), sort() and int()
  • Then there are functions found in imported modules, such as random.choice() and os.getcwd()

It is relatively easy to create your own function - technically they shouldn't be described as homemade, but as user-defined functions. At its most basic, a function in a script might look like:

#!/usr/bin/python3
def hello():
    print ("Hello World!")

hello()

The second line def hello(): tells Python this is how we define the function hello(). Generally definitions of functions are at the start of the code as Python prefers things to be defined before it uses them (that also includes new variables).
The indented part after the def statement (here print ("Hello World") ) is the instructions the function carries out.
The bottom line hello() is not part of the function but is where the program calls (i.e. uses) the new function hello(), just as when we use print("Hello") we are calling the print() function.

Brackets and Arguments

The brackets are where you can insert any arguments, i.e. pieces of information the function may act on. So for the built-in function print("Hello World"), the string "Hello World" is the argument that the function uses.
For some functions, arguments are not always necessary - they can be called with empty brackets. What arguments should be supplied is dependent on what the function is. Some functions, such as range(), can accept 1, 2 or 3 arguments, each one having a different meaning.
However, having brackets after the function name tells Python this is a function, not a variable.
Here is a modified version of the script that accepts a single string argument (here in the variable name):
#!/usr/bin/python3
def hello(name):
    print ("Hello", name)

name = input("What is your name? ")
hello(name)

And the result is:
 RESTART: C:/Users/John/Dropbox/Misc Programming/Python/python3/test07_simplefunction2.py
What is your name? John
Hello John

>>>


Function names

Function names follow similar rules to variable names (no punctuation except underscore _ and cannot start with numbers, nor should it be the same as a keyword). And whatever the name is, you should follow it with brackets () to show it is a function, not a variable.
Technically you can overwrite an existing function by using the same name, but I am very cautious about this. I would much rather use a similar but different name so the original function is still useable.

Why create more functions?

So why bother with functions? Up to this point my programs have been short and simple enough that I have not needed to use user-defined functions. But there are good reasons for using them.
  • Firstly reuse within a single program. By calling a function, you don't have to re-enter all the instructions the function carries out. This is useful when you want to do the same sort of task several times but it doesn't fit the neat repetition of a for or while loop.
  • Secondly reuse between different programs. A function is defined in a single block of code that can be copied and pasted from one script to another or run/called from a different file.
  • Thirdly ease of maintenance. If there is something that needs to be changed in the function, you only need to change it in one place. If you have simply copied and pasted the lines of code that could have been a function, you need to find and change each occurrence of the code in question.
  • Fourthly the principle of modularity: Modularity is the idea of discrete pieces of code that have a particular input and a particular output. A programmer using the piece of code only needs to know the input and the output - they don't need to know the inner workings. For example, the function print() accepts the input of a string or something that can be converted to a string, and the output is that the string appears on the command line. You don't need to know exactly how print() does that, you just know what it does. Functions allow that and therefore keep programming relatively simple and abstract. Assuming they are well-written and bug-free, User-defined functions can be just as useful in this regard as built-in or imported functions. 

No comments:

Post a Comment