Skip to content

Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Each function can be seen as a tool that solves a certain problem. The other functions can then use this tool without worrying about its structure, just for the result it gives. In order to use it, they only need to know the name of the function, the values it requires and how it returns one or more results.

Create a Function

To define a function, you write:

🐍 Python Script
def name (parameters_separated_by_comma):
    instructions
    return something #optional

Example

🐍 Python Script
def sum_of_numbers(a, b):
    result = a + b
    return result

We define a function called sum_of_numbers that receives as input two parameters a and b. It calculates the sum of the two numbers and returns the result as output.

Info

All the instructions part of the function are indented.

Use a Function

To use or call a function, you write:

🐍 Python Script
name (parameters_separated_by_comma)

When calling a function, it works just like a black box. It takes some input, processes it and gives an output.

blackBox

Input

Variables are most of the time defined locally. It means that a function isn't aware of the existence of any variables defined outside of its body. If you want to give information to your function, you need to use parameters.

Example

🐍 Python Script
def sum_of_numbers(a, b)
        result = a + b
        return result

sum_of_numbers(4, 8)
I am calling the sum function and I give 4 and 8 as parameters. When doing that, it automatically assigns the value 4 to the variable a and the value 8 to the variable b.

Output

A function has three different possibilities when it comes to the output. It can:

  • Print something on the screen.
  • Change data in the memory (for example change the content of a file).
  • It can return a value.

Let's focus here on returning a value. Variables defined inside a function only exist in that function. So if you want to give back the content of a variable at the end of your function, you need to use return.

When using return, the call to your function will be replaced by whatever is returned by the function.

Example

🐍 Python Script
def sum_of_numbers(a, b)
        result = a + b
        return result

x = sum_of_numbers(4, 8)
Here the call to my function is sum_of_numbers(4,8) and it will be replaced by result. So x = 12.