Functions are blocks of code that are run when they are called. These serve as a convenient way to break up your code into useful and named blocks so that you can use them whenever you want to.
We've already seen usages of them in past, including
Let's define a simple function in Python:
def introduction(): print("Hello from Sabe.io!")
It is that simple. Use the
def keyword to define your function, and put the code you want to execute under it while also indenting it.
Invoking a Function
What we just saw was a valid function but nothing will happen if we were to run it. That is because functions still need to be called, or invoked. Here is how we invoke it:
def introduction(): print("Hello from Sabe.io!") introduction()
Hello from Sabe.io!
Now this is great and all, but functions are much more powerful than this. We can pass in pieces of data to the function so that it can perform different tasks.
These pieces of data that we can pass in to functions are called parameters. Sticking with our previous example, let's pass in another website instead of this one.
def introduction(url): print("Hello from " + url + "!") introduction("Mixcurb.com")
Hello from Mixcurb.com!
Now that our function takes in a
url as a parameter, we can make the output refer to any website we want. Pretty powerful stuff!
Functions can return things to us. In our previous functions, they simply performed actions, like printing, but didn't give us anything back.
Let's look at an example of a function that does return something back to us:
import math def get_area_of_circle(radius): return radius * radius * math.pi radius = 4 area = get_area_of_circle(3) print(area)
get_area_of_circle function takes in the radius for the circle and computes the area for it, then returns it back. We then create a new variable
area which now holds that value. Afterwards we simply print it so see the value.
Another cool part of Python is the ability to set a default value for a parameter so that if you don't pass it in, the function is still valid and executes anyway.
Let's apply this using our previous example:
import math def get_area_of_circle(radius = 1): return radius * radius * math.pi radius = 4 area = get_area_of_circle(3) print(area) area2 = get_area_of_circle() print(area2)
Because we set the default value for
radius to be
1, when we called
get_area_of_circle without passing in a radius, it defaulted to
1 as expected. The rest of function executed normally and we got our answer.