Function definitions

https://docs.python.org/3/reference/compound_stmts.html#function-definitions

https://www.python-course.eu/python3_functions.php

INTRODUCTION

Why are we using functions?
(a) To provide the structure for your code.
(b) To reuse code (repeating code should be avoided; shorter code).
(c) To make a safe namespace [scopes].
(d) It is easier to remove bugs.

It lowers the cost for development and maintenance of the software.

+----------------+-----------------------------+
| Statements     | Examples                    |
+----------------+-----------------------------+
| Calls          | my_func(12, word="alpha")   |
| def, return    | def func(x, y=1):           |
|                |     return x + y            |
| global         | def changer():              |
|                |     global x ; x = "beta"   |
| nonlocal (Py3) | def changer(): # PEP 3104   |
|                |     nonlocal x ; x = "beta" |
| yield          | generators                  |
| lambda         | anonymous functions         |
+----------------+-----------------------------+

CREATING FUNCTIONS

A function in Python is defined by a 'def' statement (a compound statement). The argument list may be empty. If a 'return' line is not present then 'return None' is assumed. Function names should be in a joined_lower style.

The execution of a 'def' statement binds the function name in the current local namespace to a function object. The function body is executed when the function is called.

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition.


# Syntax.

@decorator   # optional
def function_name(argument_list):
    docstring   # optional
    statements
    return result   # optional

def do_nothing():   # a placeholder, it can be changed in the future
    pass            # return None

# Recommended docstrings.

def first_function(argument1, argument2):
    """Return the sum of arguments."""   # one line
    statements

def second_function(argument):
    """First line.
    (empty line)
    More lines with detailes.
    """
    statements

def func(): ...     # definition (statement)
func()              # call (expression)
other_name = func   # assignment
other_name()        # call
func.atrr = value   # defining an attribute for func
dir(func)           # the list of attributes, see dir(len)
func.__name__       # string
func.__doc__        # docstring
func(x, y)          # two arguments
func((x, y))        # one argument (tuple)

RETURNING MULTIPLE VALUES


def find_minmax(x, y):
    """Finding min and max simultaneously."""
    return (x, y) if x < y else (y, x)   # make a tuple with values

a, b = find_minmax(5, 3)   # (a, b) = (3, 5)

EXERCISES


# Create a function print_in_squares(word).
If word = "Python", them the result is
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
Try to build the whole string 'result' and print it at the end.

# Create a function print_reversed_pyramid(height).

>>> print_reversed_piramid(4)
*******
 *****
  ***
   *