Skip to main content

Python Functions

In Python, a function is a group of related statements that performs a specific task.

What is a function in Python?

Functions allow you to define reusable blocks of code in a program.

Functions can be called, receive values for use in code within them, and return values.

Functions help to break down the program into smaller, modular parts. This is very important when the program becomes very large and it is essential to keep it organized and maintainable.

Syntax

The syntax for defining a Python function is:

def function_name(arguments):
"""docstring"""
statement
statement
...
return value

where:

  • Keyword def marks the beginning of the function header.
  • The function_name is an identifier by which the function is called. It uniquely identifies the function.
  • arguments contains a list of values passed to the function.
  • A colon : marks the end of the function header and all subsequent statements must be indented to form the body of the function.
  • Optional documentation string (docstring) can be added to describe how the function works.
  • An optional return statement is used to return one or more values from the function.

Create a Function

Let's look at the simplest function that can be defined: print "Hello World!".

# function definition
def print_hello():
print('Hello World!')
note

Since Python treats def as an executable instruction, it can be declared anywhere a normal statement. So, you can nest a function inside an if, a for, a while or in any other statement.

Call a Function

After defining a function, you can call it by adding parentheses after the function name.

# function definition
def print_hello():
print('Hello World!')

# function call
print_hello()

Output

Hello World!
note

The def statement only creates the function, so it is important that the function call occurs after the execution of the def instruction.

Otherwise, we will get an error. For example:

print_hello()

def print_hello():
print('Hello World!')

# NameError: name 'print_hello' is not defined

Pass Arguments to a Function

The arguments are values passed to a function and are declared after the function name in parentheses.

note

When a function is called with arguments, the values of those arguments are copied into the corresponding parameters within the function.

# Single argument to a function
def say_hello(name):
print(f'Hello {name}')

say_hello('Alice') # print Hello Alice
say_hello('Bob') # print Hello Bob
say_hello('Tom') # print Hello Tom

Output

Hello Alice
Hello Bob
Hello Tom

If you have functions that accept multiple arguments, you can pass them separated by commas:

# Pass two arguments
def my_function(name, job):
print(f'{name} is a {job}')

my_function('Alice', 'developer')

Output

Alice is a developer

Types of Arguments

Python supports multiple types of arguments in the function definition:

  • Positional Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable Length Positional Arguments (*args)
  • Variable Length Keyword Arguments (**kwargs)

Positional Arguments

Positional Arguments are the most common arguments in Python functions.

The values of the positional arguments are copied in order into the corresponding parameters.

For example:

# Pass two arguments
def my_function(name, job):
print(f'{name} is a {job}')

my_function('Alice', 'developer')

Output

Alice is a developer

Drawback: Positional arguments must pass arguments in the order in which they are defined.

def my_function(name, job):
print(f'{name} is a {job}')

my_function('developer', 'Alice')

Output

developer is a Alice

Keyword Arguments

Keyword Arguments permits to avoid positional argument confusion.

You pass arguments to the function specifying for each value the name of the corresponding argument. In this way, arguments are matched by name and not by position (the order of arguments no longer matters).

# Keyword arguments can be put in any order
def my_function(name, job):
print(name, 'is a', job)

my_function(name='Alice', job='developer') # Alice is a developer
my_function(job='developer', name='Alice') # Alice is a developer

Output

Alice is a developer
Alice is a developer
note

It is possible to combine positional and keyword arguments in a single call: if you do so, specify the positional arguments before keyword arguments.

Default Arguments

The arguments of a function can have default values: they must be specified when the function is defined.

Default values are used if the function is called without corresponding arguments, i.e., default values make selected arguments optional.

# Keyword arguments can be put in any order
def my_function(name, job='developer'):
print(name, 'is a', job)

my_function('Alice', 'developer') # Alice is a developer
my_function('Alice') # Alice is a developer

Output

Alice is a developer
Alice is a developer

Variable Length Arguments

Variable length arguments are used to create functions that can take any number of arguments passed by the user.

This is often known as var-args or Variable Arguments.

Variable Length Positional Arguments (*args)

The use of * before a parameter allows all unmatched positional arguments to be collected in a tuple.

note

Since it is a normal tuple object, any operation supported by a tuple, such as indexing, iteration, etc., can be performed.

For example:

def print_arguments(*args):
print(args)

print_arguments(10, 20, 30, 40, 50)

Output

(1, 54, 60, 8, 98, 12)
note

The name args is standard practice, but any name can be chosen.

Variable Length Keyword Arguments (**kwargs)

The use of ** before a parameter allows all unmatched positional arguments to be collected in a dictionary, where the argument names are the keys and their values are the corresponding dictionary values.

For example:

def print_arguments(**kwargs):
print(kwargs)

print_arguments(name='Tom', surname='Nolan', age='23', job='developer')

Output

{'name': 'Tom', 'surname': 'Nolan', 'age': '23', 'job': 'developer'}
note

The name kwargs is standard practice, but any name can be chosen.

The return statement

The return statement is used to exit a function and return to the point at which it was called.

note

Once the return statement is executed, nothing else in the body of the function is executed.

# Returns the multiplication of two values
def multiply(a, b):
return a * b

print(multiply(3, 4)) # 12
print(multiply(2, 5)) # 10
print(multiply(0, 3)) # 0

Output

12
10
0

A python function always returns a value.

If no return statement is included, function automatically returns None.

:::

Return Multiple Values

Functions can also return multiple values (which is uncommon in many programming languages).

When multiple values are returned, Python packs them into a single tuple and returns it.

# Returns addition and subtraction of two values
def sum_and_sub(a, b):
return a+b, a-b

print(sum_and_sub(3, 4)) # (7, -1)
print(sum_and_sub(2, 5)) # (7, -3)
print(sum_and_sub(0, 3)) # (3, -3)

Output

(7, -1)
(7, -3)
(3, -3)
note

Since the returned value is a normal tuple object, any operation supported by a tuple, such as indexing, iteration, etc., can be performed.

note

Composition of Functions

The argument of a function can be any type of expression, including arithmetic operators or other function calls:

import math

x = math.sin(360*2*math.pi)
print(x) # -3.133115067780141e-14

x = math.exp(math.log(3.14))
print(x) # 3.1399999999999997

Nested Functions

A nested function is a function defined within another function.

Nested functions are useful for performing complex operations multiple times within another function.

def outer(a, b):
def inner(c, d):
return c + d
return inner(a, b)

result = outer(1, 2)

print(result) # 3

Output

3

Docstrings

Docstrings (document strings) are used to attach documentation to a function definition by including a string literal immediately after the function header.

note

Triple quotes are usually used for descriptions on multiple lines.

def hello():
"""This function prints
hello world
on the screen"""
print('Hello World!')

To print the docstring of a function, you can use the help() function:

def hello():
"""This function prints
hello world
on the screen"""
print('Hello World!')

help(hello)
Help on function hello in module __main__:

hello()
This function prints
hello world
on the screen

or the __doc__ attribute of the function:

def hello():
"""This function prints
hello world
on the screen"""
print('Hello, World!')

print(hello.__doc__)
This function prints 
hello world
on the screen
note

Learn more in Docstrings Chapter.

Recursion

A recursive function is a function that calls itself and repeats its behavior until a certain condition is met to return a result.

def factorial(n):
if n==0 or n==1:
return 1
else:
return n * factorial(n - 1)


print(factorial(3)) # 6
print(factorial(5)) # 120
note

Learn more about recursion in Recursive Functions Chapter.