PCEP study materials
PCEP study resources

PCEP: Functions and Exceptions

PCEP · Work through your exam, one topic at a time.

All guide sections

Functions and Exceptions

What this domain covers

PCEP checks function definition and calls, argument passing, variable scope, return values, and basic exception handling with try/except/else/finally.

Core rules

  • Define with def name(params):; call with positional or keyword arguments. Defaults must follow non-default parameters. return without a value, or no return, yields None.
  • Arguments are assigned to parameters in order; keyword arguments can be given in any order. A function can return any object, including a tuple.
  • Scope follows LEGB: Local, Enclosing, Global, Built-in. Assigning to a name inside a function makes it local unless declared global (or nonlocal for an enclosing function).
  • try runs protected code. except SomeError: catches that class and its subclasses. else runs if no exception occurred; finally always runs.
  • raise ValueError("bad") raises deliberately. Built-ins to know: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, NameError.

Worked example

def f(a, b=2): return a / b try: print(f(6, 0)) except ZeroDivisionError: print("div0") finally: print("done") Output: div0 then done. f(6, 0) overrides the default b with 0, division raises ZeroDivisionError, the handler prints, and finally always executes.

Traps

  • A mutable default such as def f(x, acc=[]) is created once and shared across calls.
  • Catching Exception before a more specific handler makes the specific one unreachable.
  • Code after raise in the same block does not run.
  • Exceptions raised in the else block are not caught by the preceding except.
  • A SyntaxError from malformed source is not caught by a runtime try.