

Functions in Python

00:00 Let’s begin by taking a general look at functions in Python.

00:05 A function is a self-contained block of code that’s designed to perform a specific task or related group of tasks. Some functions that you’ve probably encountered already might be the id() function, the len() function, the any() function.

00:21 Basically, any name that you’ve used followed by parentheses, either with something in them or not, is a reference to a function that someone else has written.

00:30 When you use a function, which we call invoking or calling a function, you only need to know its interface. Its interface consists of what arguments, if any, are passed to the function and what value or values, if any, that it returns. When you make a function call, you provide the function name and then supply appropriate values for the arguments that are expected. Then, the function carries out its task.

00:57 You don’t need to know how that’s done, you just need to know what it’s supposed to do when it’s finished. When it is finished, it returns to the spot in your program where you called the function and then you use, if needed, any of the data that it returned.

01:14 On the other hand, if you are writing a function, you determine how it performs its task. That part we call the implementation. You decide exactly what it’s going to do to carry out the steps necessary to accomplish whatever that function is supposed to do.

01:32 And then when you call your function, it’s just like calling any other function. You supply the appropriate argument values, your function then performs its task on those values if it uses any.

01:44 Then the program returns to the exact spot where you called your function, where, if needed, you should use any data that was returned.

01:55 Next, we’ll take a look at why you would want to write a function.

Become a Member to join the conversation.