Functions in Python

As the code grows the complexity also grows, functions help organizing the code.

Functions are a handy way to create blocks of code that you can reuse.

Definition and Calling

In Python use the def keyword to define a function.

Give it a name and use parentheses to inform 0 or more arguments.

In the line after the declaration the code starts, remember to indent the block of code.

Here is an example of a function called print_first_function() that only prints a phrase ‘My first function!’.

To call the function just use its name as defined.

def print_first_function():
    print('My first function!')

print_first_function()
My first function!

return a value

Use the return keyword to return a value from the function.

In this example the function second_function() returns the string ‘My second function!’.

Notice that print() is a built-in function and our function is called from inside it.

The string returned by second_function() is passed as argument to the print() function.

def second_function():
    return 'My second function!'

print(second_function())
My second function!

return multiple values

Functions can also return multiple values at once.

return_numbers() returns two values simultaneously.

def return_numbers():
    return 10, 2

print(return_numbers())
(10, 2)

Arguments

You can define parameters between the parentheses.

When calling a function with parameters you have to pass arguments according to the parameters defined.

The past examples had no parameters, so there was no need for arguments, and the the parentheses remained empty when the functions were called.

One Argument

To specify one parameter, just define it inside the parentheses.

In this example, the function my_number expects one number as argument defined by the parater num.

The value of the argument is then accessible inside the function to be used.

def my_number(num):
    return 'My number is: ' + str(num)

print(my_number(10))
My number is: 10

Two or more Arguments

To define more parameters, just use a comma to separate them.

Here we have a function that adds two numbers called add, it expects two arguments defined by first_num and second_num.

The arguments are added by the + operator and the result is then returned by the return.

def add(first_num, second_num):
    return first_num + second_num

print(add(10,2))
12

This example is very similar to the last one, the only difference is that we have 3 parameters instead of 2.

def add(first_num, second_num, third_num):
    return first_num + second_num + third_num

print(add(10,2,3))
15

This logic of defining parameters and passing arguments is the same for any number of parameters.

It is important to point that the arguments have to be passed in the same order that the parameters are defined.

Default value.

You can set a default value for a parameter if no argument is given using the = operator and a value of choice.

In this function, if no argument is given, the number 30 is assumed as the expected value by default.

def my_number(my_number = 30):
    return 'My number is: ' + str(my_number)

print(my_number(10))
print(my_number())
My number is: 10
My number is: 30

Keyword or Named Arguments

When calling a function, the order of the arguments have to match the order of the parameters.

The alternative is if you use keyword or named arguments.

Set the arguments to their respective parameters directly using the name of the parameters and the = operators.

This example flips the arguments, but the function works as expected because I tell which value goes to which parameter by name.

def my_numbers(first_number, second_number):
    return 'The numbers are: ' + str(first_number) + ' and ' + str(second_number)

print(my_numbers(second_number=30, first_number=10))
The numbers are: 10 and 30

Any number of arguments: *args

If you don’t want to specify the number of parameters, just use the * before the parameter name, and function will take as many arguments as necessary.

The parameter name could be anything like numbers, but there is a convention in Python to use args for this difinition of a variable number of argumetns.

def my_numbers(*args):
    for arg in args:
        print(number)

my_numbers(10,2,3)
10
2
3

Any number of Keyword/Named arguments: **kwargs

Similar to *args, we can use kwargs to pass as many keyword arguments as we want, as long as we use .

Again, the name could be anything like numbers, but kwargs is a convention.

def my_numbers(**kwargs):
    for key, value in kwargs.items():
        print(key)
        print(value)

my_numbers(first_number=30, second_number=10)
first_number
30
second_number
10

Other types as arguments

The past examples used mainly numbers, but you can pass any type as argument and they will be treated as such inside the function.

This example is taking strings as arguments.

def my_sport(sport):
    print('I like ' + sport)

my_sport('football')
my_sport('swimming')
I like football
I like swimming

This function takes a list as argument.

def my_numbers(numbers):
    for number in numbers:
        print(number)

my_numbers([30, 10, 64, 92, 105])
30
10
64
92
105