Skip to main content

P01.4 · Functions and scope

A free, illustrated module of 4 lessons and one interactive in P01 Python from Zero: Defining and calling a function; Parameters and arguments; The call stack; Scope: where Python looks up a name.

P01.4 L0 · Foundation 4 lessons · about 100 min Live · in review

Part of P01 Python from Zero in the Programming and Data track.

A function gives a name to a block of code, takes inputs and hands back one value. These four lessons write functions with def and return, follow a call through its four steps, match arguments to parameters by position, by keyword and by default, draw the call stack that gives every call its own frame of names (recursion included), and settle where Python looks when it meets a name. The course’s model predict(hours) is a function, and so is every model in machine learning.

What you need first. Values, names and assignment, drawn as memory diagrams (P01.2), and if, loops and the loop patterns that total, count and search a list (P01.3). Nothing is imported: the code uses only what P01.1 to P01.3 teach, plus the functions it builds.

Lessons

  1. Defining and calling a function P01.4.1 25 min

    A function gives a name to a block of code with inputs and an output. Write one with def and return, follow a call through its four steps, tell returning a value from printing it, and document a function with a docstring that help can read.

  2. Parameters and arguments P01.4.2 25 min

    Arguments reach parameters by position or by keyword, and a parameter may carry a default. Learn the three rules Python uses to match them, the errors it raises when a match fails, and how to read a signature in the documentation, type hints included.

  3. The call stack P01.4.3 25 min

    Every call gets a frame of its own that holds its local names, pushed when the call starts and popped when it returns. Trace the stack for squared_error and predict, watch factorial call itself four frames deep, and see why a missing base case ends in RecursionError.

  4. Scope: where Python looks up a name P01.4.4 25 min

    When Python meets a name it looks in four places in a fixed order: the running function, any enclosing function, the file’s global names, then the built-ins. Learn the order, why assigning inside a function makes a name local, and how hidden globals and reused built-in names cause bugs.

The interactive

P01.4-X1 · Call-stack stepper. Step through a program in which squared_error calls predict, or through factorial(n) with n chosen by a slider from 0 to 5. Frames are pushed with their own names, returned values travel back to the caller, and frames are popped; a read-out gives the depth of the stack and the value just returned. It lives in The call stack.

Back to top