From the course: Building Recommender Systems with Machine Learning and AI

Functions in Python

- [Instructor] Okay, moving on to functions now. Fortunately, they work pretty much like you'd expect in Python. The syntax looks like this. You define a function with the def keyword, followed by the function name, followed by any parameters you want to pass in with their names. Be sure to end the function definition with a colon. After that, your code within the function needs to be indented. Python is all about the whitespace remember. So here, we have a super simple function called SqaureIt that takes in one value, calls it x, and returns its square. Calling the function works exactly like you'd expect. Just type in SquareIt and 2 in parentheses to get the square of two for example. Let's run it. There are a few funky things you can do with functions in Python. For example, you can actually pass in another function to a function as a parameter. This is something that allows Python to play nice with functional programming languages, which you encounter a lot in distributed computing. We can create a function like this called DoSomething that takes in some function F, some parameter X, and returns to result of F of X. So we can actually say DoSomething, SquareIt, 3 as a really convoluted way of getting back the square of three. But it works. By the way, did you notice that this block of code still knows that the SquareIt function exists even though we defined it in a previous block? Jupyter Notebooks run within a single kernel session, so anything you define or modify before the block you're running, will still be in memory within that kernel. Sometimes this can lead to confusing behavior, especially if you're running blocks within a notebook out of order or repeatedly. If weird things start happening, you can always start from a clean slate by selecting kernel restart from the menu. Let's also give some attention to lambda functions. These allow you to pass around simple functions inline without even giving them a name. You see this pretty often in the world of data science. It's easiest to understand with an example. Here we're calling our DoSomething function with the lambda function that computes the cube of a value instead of its square. Take a look at the syntax here. We say lambda, followed by the function parameter, followed by a colon, after which we can do what we want to that parameter. Whatever value is computed after the colon is implicitly the return value of the lambda function. So this says to create a lambda function that takes in something called X and returns X times X times X. We passed that lambda function into DoSomething with a value of three, which then executes our lamdba function for the value three. And if we run this, you can see that we do indeed get back 27, which is three cubed.

Contents