Locked learning resources

You must own this product to watch this lesson.

Locked learning resources

You must own this product to watch this lesson.

An Example Function

This lesson is from the Real Python video course by Christopher Bailey.

00:00 In order to talk about decorators, I need to first talk about functions, so you’ll start with an example function. A function is made up of a couple parts.

00:08 It starts with a header, initially with def—short for define—at the beginning, and then the function’s name, followed by parentheses and a colon.

00:17 I’ll discuss what can go in those parentheses in a moment. Below it, you can have a docstring that will describe what this function does—a very good habit. And then below your header, you have the statement.

00:28 The statement is the code that will run when the function is called.

00:32 In order for you to call the function, you use the function’s name and the pair of parentheses. As the article that this tutorial is based upon states, “a function returns a value based on the given arguments.” Arguments, also known as parameters, are what go in those pair of parentheses. Arguments then can be used inside of the function to return values. For this case—let’s say it’s an integer—then my_var is being set to that argument * 5, and that variable is then returned. So again, a very simple example, but you can have multiple arguments, and at the end of the statement, you could be returning multiple values. Let me show you some examples.

01:11 For this example, I’ll be using a REPL named bpython.

01:17 Let me have you make a function. Define the function, then give it a name. In this case, the parameter that we’re putting in is a number.

01:31 Here’s your docstring. And lastly, you will return the number + 1.

01:37 So what happens if you type in add_one? You’ll see that add_one is a function. This is the memory location it’s in. So to call it, we need to add our parentheses. If we put nothing inside there, the interpreter gives you an error saying that this function requires one positional argument, 'number'. So, add 1 to 3, and your function returns 4.

02:01 Add 1 to 9, and you get 10. So, this object add_one—can you copy it also? Sure. So, try this out. Make another variable, add_one_also, and copy add_one into it.

02:15 So, technically, what is add_one_also? If you hit Return, you’ll see that it’s a function. It shows as a reference to add_one, and it’s in the exact same memory location.

02:27 As a function, add_one_also() works the same. Add 1 to 11, and you get 12. So, what does that mean? Functions are first-class objects, just like any other object.

02:40 Let me explain that a little bit deeper next.

You must own this product to join the conversation.