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.returnwithout a value, or noreturn, yieldsNone. - 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(ornonlocalfor an enclosing function). tryruns protected code.except SomeError:catches that class and its subclasses.elseruns if no exception occurred;finallyalways 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
Exceptionbefore a more specific handler makes the specific one unreachable. - Code after
raisein the same block does not run. - Exceptions raised in the
elseblock are not caught by the precedingexcept. - A
SyntaxErrorfrom malformed source is not caught by a runtimetry.