Skip to content
AI-grafen
DAI developerProgramming· about 45 min· fundamentals that rarely change· verified 2026-09-20· EN

Python — functions, scope and exceptions

Be able to write functions with default values, understand scope, and handle exceptions with try/except.

Prerequisites

Intuition

A function is a contract: arguments go in, a return value comes out. Three things that separate beginner code from good code:

  1. Default values: def train(data, epochs=10, lr=0.01) — the caller only has to give what deviates.
  2. Scope: variables inside the function exist only there. A function that changes global variables is hard to test — return instead.
  3. Exceptions: when something does not work (a missing file, the wrong type) the function should say so with raise, not return −1 and hope somebody checks.

Code

def mean(values, *, ignore_empty=False):
    """The mean. An empty list is an error unless ignore_empty=True (then 0.0)."""
    if not values:
        if ignore_empty:
            return 0.0
        raise ValueError("an empty list has no mean")
    return sum(values) / len(values)

print(mean([1, 2, 3]))                  # 2.0
print(mean([], ignore_empty=True))      # 0.0
try:
    mean([])
except ValueError as e:
    print("error:", e)

x = 10
def f():
    x = 5            # local — the global one is untouched
    return x
print(f(), x)        # 5 10

The * in the signature forces ignore_empty to be given by name — which makes the calls readable.

Mastery means

  • Writes functions with default values and keyword arguments
  • Explains scope: local vs global
  • Handles exceptions with try/except and raises its own

Sign in to do the exercises and build your mastery up.

Sources

All the sources and licences