Basics#

A function has a name, which is used to call the function. A function can take arguments to control its behavior, and a function may return a value, which then can be used by the calling code.

Function Definition#

Functions are defined as follows in Python:

def my_function(argument, another_argument, more_arguments):
    # indented block of code

Returning Values#

If a function shall return a value, then its code block has to contain the following line at least once (usually the last line):

return some_value

The return keyword immediately stops execution of the function’s code and hands control back to the calling code, which then can use the content of some_value.

If there is no return keyword in a function, then the function ends after executing its last line and returns None. In this sense, Python functions always return a value.

Function Calls#

A function is called es follows:

a = my_function(value_for_argument, value_for_another_argument, values_for_more_arguments)

After finishing execution of the function’s code a contains the return value of the function. If the function does not return a value or the return value is not needed by the calling code, then the assignment a = ... can be omitted.

Documentation Strings (Docstrings)#

In Python by convention every function definition contains a triple quoted documentation string. This string is ignored by the Python interpreter, but read by tools for automatic generation of source code documention.

def my_function():
    '''Does nothing.
    
    Takes no arguments und returns nothing.
    '''
    # some code

For some formatting conventions see Python documention. More details: PEP 257. There are many different conventions for docstring formatting. PEP 257 is only one of them.