Day 5
Functions are used in most object orientated languages to perform a piece of code multiple times. We call this a function because it can be re-usable over and over again so you don't have to repeat code. The idea is that most things that happen in your python program will be functions. This allows your basic program code to be very simple, and the real work is done inside the functions.
Code:
def hello(x):
return 'Hello to ' + x
print hello('Zag')
What happens here is we define a function called "hello" in the first line, then tell the function to return the text "Hello to" and then the variable "x". The last line just calls the function and sends the parameter "Zag" which assigns "Zag" to the x variable, then runs the function code which writes the full line of text "Hello to Zag". As you can see, the fact that we can send a variable to the function now means it has unlimited possibilities to process the text easily and quickly. This is a very simple example but functions can be far more complex doing lots of different things with different data.
Now lets look at how we can send default parameters to the function.
Code:
def name(first='zag',last='Kodi'):
print '%s %s' % (first,last)
name ()
name (last='XBMC')
So its basically the same but we are defining a default value to the first and last names. This function can now be called with no parameters "name ()" at all and return the default variable names. Or we can override them with our own values such as "name (last='XBMC')". This is useful because we may want to always have a default variable for common operations.
Sometimes you won't know how many parameters you want to have, so python allows you to have an unknown number of parameters passed to a function like this:
Code:
def list(*food):
print food
list ('apples', 'beef', 'beans')
All that we are doing here is defining a parameter in the function that is a tupple with the asterisk *. This means it can be any number of data items sent to the function. When we call the function list later, we can enter lots of different food types and all of them will be printed to the screen no mater how many we use. You can mix and match static parameters or mutiple parameters by defining them in the function on the first line.
Hopefully this gets you on your way with functions, they will be the building blocks of most of your programs. Its always best to put code into functions because it should simplify your code, and organize it better, it also helps with keeping things consistent and for better debugging. Just remember to make sure anything that the user inputs is the correct variable type!