Mastering the use of lists and loops is one of the 5 fundamental skills of building algorithms:
Basically, a function is a bunch of code wrapped between brackets that you can run anytime whenever you decide. For example:
def multiply(a,b): return a*b result = multiply(2,6) print(str(result)) # Output: 12
By reviewing that code we can obtain the following conclusions:
defwe have to write the name we want for the function (in this case "multiply").
,. We can pick the name the parameters are going to have, but they must always be in the same order.
:that way the computer will know we are about to start coding the insides of the function (the function algorithm).
From now on, I have the function
multiply available on my code, and I can re-use it as many times as I need to multiply two values like this:
result = multiply(2,6) print(str(result)) # Output: 12 result2 = multiply(5,2) print(str(result2)) # Output: 10
📺 Click here to watch a short video explaining functions (9min)
This function calculates the cost of organizing a party with the following criteria:
def get_price(number_of_guests): price_per_guest = 10 total_cost = price_per_guest * number_of_guests if number_of_guests > 200: total_cost = total_cost - (total_cost * 0.1) # ← 10% discount return total_cost
The whole idea is to have a library of hundreds of functions and use them as we please, you declare all your functions and later you start using and re-using them all the time.
Coding is very abstract and it happens a lot that you have no idea what your wrote yesterday. Before functions existed, algorithms were this huge never-ending series of lines of code where developers would have a hard time and get lost. It is hard for your brain to follow a procedure/algorithm of great length; the more lines of code, the more abstract it becomes.
By using functions you have the following advantages:
If you think about it, functions are the equivalent of books. The store knowledge and ways of doing things and in future developments you just re-use them instead of having to figure out everything all over again.
All functions must start and end somewhere, that its called the scope of the function. You can delimit the boundries using curly brackets like this:
# this part of the code is OUTSIDE the 'multiply' function def multiply(a, b): # this part of the code is INSIDE the 'multiply' function return a * b # this part of the code is INSIDE my function but it will never # be executed because it is located AFTER the return statement. } # this part of the code is OUTSIDE the 'multiply' function
Any variables that you declare inside the function will not be available outside of it.
def multiply(a, b): myVariable = 'hello' return a * b # this print won't work it will trigger an error) because myVariable was # declared inside the function multiply, therefore it is not available outside. print(myVariable)
☝ It is very important to remember that once you use the
return statement the function will stop executing, if there is any code after that statement it will never be executed.
If you function it's going to be a one line function, you can use the "lambda" trick to be more agile. You have to use the reserved word
multiply = lambda a, b : a * b result = multiply(2,3) print(str(result))
Lamba is ideal for cases in which you have little functions, you will learn to love it because it makes your cod really fast and agile to code, specially when you are working with arrays.
The only way to use (a.k.a: call) a function is to use parenthesis brackets like this:
# this is how you call a function without parameters multiply() # this is how you call a function with parameters multiply(<first param>,<second param>) # for example, to multiple 3 times 9 multiply(3,9)
Please remember to assign the function whatever parameters it should receive. In our example, the multiply function was declared asking for two numbers to multiply. Play with the following example as you like:
You can combine functions however you want and have chained calls like this:
def sum(a,b): return a+b def multiply(a,b): return a*b; print(multiply(sum(3,5),sum(1,1))) # the execution goes from inside to outside # first, the sum of 3+5 and 1+1 will be calculated # then, their respective results will be multiplied firstSum = sum(3,5) secondSum = sum(1,1) print(multiply(firstSum, secondSum))
The following code has 3 functions declared:
def get_average(ages): #some code here def get_youngest(ages): #some code here def get_person_info(name): #some code here
As you can see, the function names are pretty specific on what the functions do, as well as the parameters assigned to them.
Other important things to notice:
get_averageis to get the average value on a given array. It knows nothing else and that is great! By separating your code into little functions, you can focus on one thing at a time.