From the course: Building the Classic Snake Game with Python

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Avoiding repetition by using Lambda expressions

Avoiding repetition by using Lambda expressions - Python Tutorial

From the course: Building the Classic Snake Game with Python

Avoiding repetition by using Lambda expressions

- Currently, we have multiple callbacks for changing the snake's direction in response to key presses. So for example, we've got go up, which is very similar to go right and the other two. There is a way to avoid this repetition by using Lambda expressions to pass additional arguments to a callback function. In this way, we can have just one function to handle changing this next direction, which responds differently depending on the argument it receives. We define the callbacks in a single function called a bind direction keys. So let's do that now. (keyboard clicking) So we're going to do screen dot on key. And now, instead of naming a particular function that we've already defined, we're going to use a Lambda expression. (keyboard clicking) So in this situation that's like an anonymous function. So it's going to be set snake direction, which we haven't yet written, set snake direction. So that's the function. And we're going to pass the argument up and that's going to be in response…

Contents