Functions

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 print().

Let's define a simple function in Python:

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:

PYTHON
def introduction(): print("Hello from Sabe.io!") introduction()
BASH
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.

Parameters

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.

PYTHON
def introduction(url): print("Hello from " + url + "!") introduction("Mixcurb.com")
BASH
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!

Return Values

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:

PYTHON
import math def get_area_of_circle(radius): return radius * radius * math.pi radius = 4 area = get_area_of_circle(3) print(area)
BASH
28.274333882308138

Our new 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.

Default Parameter Values

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:

PYTHON
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)
BASH
28.274333882308138 3.141592653589793

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.

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.