# Python: functions

A function is a named piece of code that takes values and returns a result. In Python a definition takes one line, but arguments have subtleties: defaults are evaluated once, positional and keyword arguments mix by rules, and a function without return still returns something.

## Definition and return

A function starts with the word `def`, a name, parentheses with the parameter
list and a colon. The body is indented by four spaces.

```python
def greet(name):
    """Return a greeting for the given name."""
    return f"Hello, {name}!"

print(greet("Anna"))     # Hello, Anna!
```

The triple-quoted string right under `def` is the function's docstring; it is
available through `help(greet)` and `greet.__doc__`. Writing one pays off even
for yourself: a month later it is the only way to remember what the function
promises.

If no `return` runs, the function returns `None` — nothing crashes, the result is
simply empty:

```python
def add(a, b):
    print(a + b)        # prints, but does not return

result = add(2, 3)      # 5
print(result)           # None
```

Mixing up `print` and `return` is beginner mistake number one. `print` shows a
value to a person; `return` hands it to the code.

## Arguments: positional, keyword, with defaults

```python
def power(base, exp=2):
    return base ** exp

print(power(3))              # 9
print(power(3, 3))           # 27
print(power(exp=3, base=2))  # 8
```

Positional arguments are matched by order, keyword arguments by name, and the
latter can come in any order. Parameters with default values are declared only
after the ordinary ones: `def f(a=1, b)` is a syntax error.

An asterisk in the parameter list makes everything after it keyword-only — that
saves you from unreadable calls like `save(data, True, False)`:

```python
def save(data, *, overwrite=False):
    return f"{data} / overwrite: {overwrite}"

print(save("report", overwrite=True))   # report / overwrite: True
```

## A variable number of arguments

`*args` collects extra positional arguments into a tuple, and `**kwargs` collects
keyword arguments into a dictionary.

```python
def total(*args, **kwargs):
    print(args, kwargs)
    return sum(args)

print(total(1, 2, 3, discount=5))
  # (1, 2, 3) {'discount': 5}
  # 6
```

The same asterisk works in a call too — it unpacks a ready sequence or dictionary
into arguments:

```python
nums = [2, 3]
print(power(*nums))                      # 8
print(power(**{"base": 5, "exp": 3}))    # 125
```

## The mutable default value

A default expression is evaluated once — when the function is defined, not on
every call. So a list or dictionary used as a default lives on between calls:

```python
def collect(item, box=[]):
    box.append(item)
    return box

print(collect("a"))   # ['a']
print(collect("b"))   # ['a', 'b']  — not what you expected
```

The fix is always the same: use `None` as the default and create the real value
inside.

```python
def collect(item, box=None):
    if box is None:
        box = []
    box.append(item)
    return box

print(collect("a"))   # ['a']
print(collect("b"))   # ['b']
```

## Scope

A name assigned inside a function is treated as local for the whole function —
even if the assignment is on the last line.

```python
counter = 0

def bump():
    global counter
    counter += 1

bump()
print(counter)      # 1
```

Without the `global counter` line, the same code would fail with
`UnboundLocalError`. But `global` is a bad habit: more often you should take the
value as an argument and return the new one. Reading global values inside a
function works without any declaration.

A little practice: write a function `stats(*numbers)` that returns a tuple of the
minimum, maximum and mean, and check that it works both as `stats(1, 2, 3)` and as
`stats(*[1, 2, 3])`. Next you will want [Python decorators](https://skillok.org/topics/python-decorators)
— they are add-ons built on top of functions — and
[Python exceptions](https://skillok.org/topics/python-exceptions), to report bad arguments cleanly.

## Step-by-step plan

1. **A simple function with return** — Write a function that takes two numbers and returns their sum; print the result.
2. **Defaults and keyword arguments** — Add a parameter with a default value and call the function three different ways.
3. **Collect *args** — A function with a variable number of arguments that computes the mean; call it by unpacking a list.
4. **Reproduce the trap** — Run the box=[] example twice in a row and see the list accumulate values.
5. **Rewrite it safely** — Change the default to None and check that calls no longer affect each other.

## Check yourself

1. What does this print: def f(a, b=2): return a * b; print(f(3))?
2. What does this print: def f(x): print(x); r = f(1); print(r)?
   - 1, then 1
   - 1, then None
   - None, then 1
   - An error
3. What does the second call print: def c(i, box=[]): box.append(i); return box; c('a'); print(c('b'))?
   - ['b']
   - ['a', 'b']
   - ['a']
   - []
4. What does this return: def t(*args): return len(args); t(1, 2, 3, 4)?

## Sources

- [Python tutorial: defining functions](https://docs.python.org/3/tutorial/controlflow.html) — The section on def, defaults, *args and **kwargs
- [Built-in functions reference](https://docs.python.org/3/library/functions.html) — sum, min, max, sorted and other functions to check your solutions with
- [PEP 8 — Style Guide](https://peps.python.org/pep-0008/) — How to name functions and parameters

---

https://skillok.org/articles/en/python-functions
