Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Functions

Open in Colab

A function takes some number of inputs, and returns some number of outputs. Recall the keywords def, and return

You can look up a function call signature and documentation with help()

You can also use ? in ipython

If we want to provide a docstring, we can do so in the function declaration

Keyword Arguments

You can provide keyword arguments by setting a default value

keyword arguments must come after regular arguments

Unpacking

In Python, it is common to see function calls of the form

args is a tuple containing the arguments

kwargs is a dict containing keyword arguments

You can also unpack containers in other contexts

This is very useful for passing along arguments to other functions without having to even know what the possibilities are.

A good way to extract keyword arguments from kwargs is to use the get method for Python dictionaries

Helper Functions

You can define helper functions inside the definition of a function

Lambda Functions

A Lambda Function is an anonymous function, meaning you don’t give it a name e.g. by declaring it in a def block.

lambda functions (and the lambda calculus) play an important role in the theory of computing. They can be found in a many languages other than Python.

The semantics of a lambda function are very similar to a function declared using def:

lambda *args : outputs

Exercises

  1. Define a lambda function that acts as the identity on input arguments

Notebook Cell
  1. Define a function that plots a 2-dimensionsional function using plt.imshow. Pass along keyword arguments to the imshow function

  1. Define a function that computes the sum of its arguments

Notebook Cell