Skip to content

Python Functions

Learn how to define, call, and use Python functions with arguments, return values, and advanced features like positional, keyword, default, and variable-length arguments.

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!".

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

Call a Function

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

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

print_hello()

Output

Hello World!

Pass Arguments to a Function

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

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:

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:

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

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

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.

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.

For example:

def print_arguments(*args):
    print(args)

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

Output

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

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'}

The return statement

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

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.

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)
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

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
Navigation