Lecture 4.1 · Interactive lab

Functions Lab

Watch call frames open and close, match arguments to parameters, and see what a function can change

Introduction to Data Science and Machine Learning
Md Mahbub E Noor · University of Barishal
All labs

Call visualiser: frames appear, values go in, values come back

Every example from the lecture. Watch Python skip the function body at def, open a new frame at each call, and remove it at return.

What to notice

  • def only stores the function. Its body runs at the call.
  • Each call gets a fresh frame. Its names disappear when the call ends.
  • A function without return gives back None.
  • Untick "numbers and text inside the frame" to see that every name points to an object.

Try this

Argument matcher: which value goes into which parameter?

Pick a function, type a call, and see how Python matches arguments to parameters: by position, by keyword, or from a default. Wrong calls show the real error.

How the arguments are matched

What to notice

  • Positional arguments fill parameters left to right. Keywords fill by name, in any order.
  • Positional arguments must come before keyword arguments in a call.
  • A default is used only when nothing else filled that parameter.

Try this

Change the object, or move the name?

A parameter is a second name for the caller's object. Choose what the function does with it, predict whether the caller sees a change, then check.

After the call, does outside look different?

Your results so far

What to notice

  • Methods like append and item assignment change the object, so every name for it sees the change.
  • lst = ... or n = n + 1 only moves the local name. The caller's name still points to the old object.
  • Numbers and text can never be changed in place. To send a new value out, return it.
  • Surprise: lst += [100] changes the list in place, but lst = lst + [100] does not.

Try this

Write and test: functions that return their answer

The in-class exercises and homework, with automatic tests. The expected answers were produced by running a correct solution in real Python.

Test results

Printed while testing

What to notice

  • The tests check what your function returns, not what it prints.
  • "got None" usually means a missing return, or a return inside the loop that ends it too early.
  • Your code is saved in this browser, so you can come back to it.

Try this

Works offline: no internet needed. The Python shown here runs in your browser with the same rules as Python 3, so results and error messages match what you will see in Jupyter.