Transcript for:
Teaching Karel to Turn Right

Hi, in this video we're going to address an important problem that you may have noticed, and it's the problem that Karel can't turn right. So let's revisit our "Build a Tower" program. In this program, we wanted Karel to build a stack of three tennis balls and then end up on top of the tower facing east. You may have ended up in a spot like this in your program. Karel was on top of the tower, and what you wanted is Karel to turn right. So maybe you wrote a command like this: turnRight, open paren, closed paren, semicolon, because that's what you wanted Karel to do and Karel can turn left. But when you may have tried this, you'll notice that Karel can't turn right. This would have thrown an error. This is not one of the commands that the dog knows. So instead, what you may have figured out is that you need to say: turnLeft, turnLeft, turnLeft. You need to say that three times to accomplish the same task. But don't you wish you could say "turnRight"? That's really what you want to tell the dog to do, but the dog doesn't know that command. So the answer? Introducing functions! Functions are the way to teach Karel new words. So what is a function? A function is a way to teach Karel a new word, a new behavior that he doesn't know. So what we want to do is teach Karel how to turn right. So what that means is that we'll write a function called turnRight, and this is what it looks like. We first write the keyword "function", space, and then turnRight, which is the name of our function, open parens, closed parens, open curly brace, and then the three commands that we want, the recipe for how to turn right. So turning right for Karel is the same as turning left three times, and then we end with a closed curly brace. So let's look carefully there: turnRight is the name of the function. These open curly brace and closed curly brace specify what is inside that function. Everything between those braces is the function body. So here, this is the recipe for how to turn right. These are the instructions. So now let's go into our code editor and make this happen. So here we have the program where Karel builds the tower and if I reset and run it, we'll see that we're almost at the point where Karel can turn right. So I'll say turnRight, and if I call that, uh-oh, we see we get an error. "turnRight" isn't defined. So let's define it: function, turnRight, open parens, closed parens. And then here the way we type the rest of our function is we write: open curly brace, closed curly brace, and we put our cursor in the center and hit enter a few times, and this is where our code is going to go to define the instructions for how to turn right. So we say turnLeft, turnLeft, turnLeft. This is teaching Karel how to turn right. So let's reset our program and run. [Program running.] And we see it does what we wanted. Karel is now turned right.