What are Functions?

This lesson provides an in-depth look into the most powerful feature of Python programming: functions.

Definition

A function is a reusable set of operations.

That sounds like a pretty straightforward definition. But what does it exactly mean?

Take the print() and len() statements for instance. Both always perform predefined tasks. Hence, they are examples of functions!

Why Use Functions?

Think of a function as a box which performs a task. We give it an input and it returns an output.

We don’t need to write the set of instructions again for a different input, we could just call the function again.

Functions are useful because they make the code concise and simple. The primary benefits of using functions are:

  • Reusability: A function can be used over and over again. You do not have to write redundant code. For example, a sum() function could compute the sum of all the integers we provide it. We won’t have to write the summing operation ourselves each time.

  • Simplicity: Functions are easy to use and make the code readable. We only need to know the inputs and the purpose of the function without focusing on the inner workings. This abstraction allows us to focus more on gaining the output instead of figuring out how it was computed.

An input isn’t even necessary. A function could perform its own computations to complete a task.

Get hands-on with 1200+ tech skills courses.