Functions in Python 3

A function is a named sequence of statements. Since a function is named, it is reusable. A simple function example:

def hello_function():
    '''This is where the function documentation goes'''
    print('Hello from function')

Hello from function
<function hello_function at 0x7f34bc7db378>
  • The def keyword is used to define a function.
  • It is followed by the function name, argument list(if any), and a colon :.
  • The function body is indented by 4 spaces.
  • The first line of a function body is a docstring, which is documentation for the function. It’s a good practice to always include the docstring.
  • The statements that constitute the function are placed after the docstring.
  • A function is an object, notice the output of print(hello_function).

A function can return a value after it finishes execution. If a return value is not specified, the default value is None. Example:

def function_with_return():
    '''This function returns a number'''
    return 42
return_value = function_with_return()

The return keyword is used to return a variable or value.

A function can accept arguments. Example:

def function_args(arg1):
    '''Prints the argument it recieves'''
function_args('My argument')
My argument

It is possible to have default arguments. When an argument is not provided, a default value is used. Example :

def function_default_args(arg1=42):
    '''A function with a default argument'''

Keyword arguments are specified by explicitly stating which argument a value belongs to. Very poor explanation, let the code speak:

def function_kwargs(name='no name', age=42):
    '''Keyword arguments demo'''
    print(name, ' ', age)
function_kwargs(age=34,name='my name')
function_kwargs(name='my name',age=34)
my name   34
my name   34

It is possible to mix keyword and positional arguments. Keyword arguments should always come after positional arguments. The official ducumentation explains this concept well.

Arbitrary argument lists are those whose content length can vary. Example:

def function_variable_args(*args):
    '''This function prints a variable number of arguments'''
    print(' '.join(*args))
variable_args1 = 'python', 'ruby', 'php'
variable_args2 = 'python', 'ruby', 'php', 'java'
python ruby php
python ruby php java

I don’t understand arbitrary argument lists well. The same result can be achieved by using a normal tuple without the *args. I’ll come back to this later.

The official documentation also contains tl;dr about the coding style in Python. Link here.

To understand how arguments are passed to functions and how arguments being mutable or immutable affects the values in the outer scope, refer here.

Code for today’s plog is here.