def add(a, b): return a+b
What this does is it defines the function add(). "a" and "b" are parameters that are requested upon calling it (not when you define it). It then does addition with "a" and "b" and returns them. So calling it could look like this:
c = add(5, 3) #this would make print(c) #output the number 8
Functions are fairly simple but powerful if used correctly.
A few notes about functions:
Functions uses their own namespace, meaning that they have their own set of variables unless specifically told otherwise. It's a good practice to let it use it's own variables and return the necessary values though.
Functions will be exited upon return command. Meaning that when return is called the function will be exited and the code coming after it will be ignored.
I have found this useful while doing recursions. Or if I have stacked up for loops and want it to end after a criteria is met (be careful not to overuse it though).
Now let's say you have a function that you want to have parameters with default but changeable values. This is easily done by this method:
def function(a, b, c=2, d=3, e=7): print('hi')
In this function you have to enter a value for "a" and "b" but c,d and e will default at 2, 3 and 7. If you want to enter a value for say e. You do so in this manner.
function('value for a', 'value for b', e='value for e')
This way you don't have to enter a value for c and d too.
That pretty much concludes this tutorial. I was planning on having classes in here too but realized it was a little too much for me atm. However i will do classes in a later tutorial.
Stay tuned for part 5 where I'm gonna go through the usage of modules.
Feel anything have been left out? Had trouble with something? Or want something changed?
Post a comment about it and I will see what I can do.