Chapter 3: Custom functions

Functions - Recap

face Josiah Wang

If you remember, a function is a ready-made building block that you can just reuse and plug into your program.

You do not need to know what goes on inside the building block. As long as you know what the function expects as an input, and what the function produces as output, you can treat it as a black box.

Functions as a black box

You have so far learnt how to call existing functions from the Python standard library, such as abs(), len(), round().

Recall that to call a function, you will need to know:

  1. The name of the function
  2. The input arguments the function can take
  3. What the function does (at a high level), for example “compute the absolute value”
  4. The output the function returns

Calling a function is as simple as calling it by its name, and passing any input arguments that are required, e.g. abs(-4)

A function will return an object, for example abs(-4) returns 4, and you can assign this object to a variable (e.g. x = abs(-4)).

A function call

A function might also return None, which is a special object representing “nothing”.