BeginnerTopic 7 of 104Software & Computing

Functions

Reusable named blocks that take parameters and return values.

In depth

Functions package reusable logic with parameters and return values. Benefits: abstraction, testing and avoiding repetition. Ideas: pure functions, default and keyword arguments, scope, recursion, higher-order functions and lambdas. Keep functions small and well named.

Key points

  • Call stack
  • Pass by value vs reference
  • Docstrings
Example

def area(r): return 3.14159*r*r.

Why it matters

Functions break a program into reusable parts, which makes code easier to test, change and understand.

Where this is used

  • Writing a unit conversion function used in many places.
  • Separating the logic that reads a sensor from the logic that displays it.
  • Creating a function that validates an email address.

Frequently asked questions

What is Functions?

Reusable named blocks that take parameters and return values.

Why is it important to understand functions?

Functions break a program into reusable parts, which makes code easier to test, change and understand.

What makes a good function?

It does one clear job, has well-named parameters, returns a predictable result and avoids hidden changes to shared state.

What is a side effect?

A change outside the function, such as writing to a file or changing a global variable, which makes behaviour harder to predict.

How is Functions used in practice?

Typical applications include writing a unit conversion function used in many places, separating the logic that reads a sensor from the logic that displays it and creating a function that validates an email address.

What should I learn before Functions?

Study "Loops" first (topic 6 of 104 in Software & Computing). It covers the groundwork this topic builds on.

What are the key points of Functions?

Call stack. Pass by value vs reference. Docstrings.

Can you give an example of Functions?

def area(r): return 3.14159*r*r.

What comes after Functions?

The next topic is "Arrays and lists", which builds directly on this one.

How difficult is Functions?

It is classed as Beginner in Software & Computing (topic 7 of 104). It is an entry-level topic. It relies only on basic school mathematics and the ideas introduced earlier in this discipline.

Learning path

Want to practise? Open the interactive course for quick checks, quizzes, simulations and progress tracking.

Related topics