As you know, Reeborg is not exactly in good shape. He can only turn left, has an oil leak, can only see walls when they are right next to him and hear beepers when he is literally standing on top of them. Reeborg has also a (somewhat broken) compass which he can use to find out whether he is facing north ... or not. To find out if he is facing north, you can ask Reeborg to do the test facing_north().
Write a short program that will ensure that Reeborg will turn left until he faces north and then turn itself off, no matter what his starting orientation is.
The tests that Reeborg performs are actually Python functions. The result of these functions is not to print out a value, like we have seen so far, but rather to obtain an answer (True or False in this case) that can be used afterwards. To do something similar ourselves, we need to use the Python keyword return. Here's an example:
>>> def add(a, b): ... answer = a + b ... return answer ... >>> c = add(4, 5) >>> print c 9 >>> # We can print directly the output of the function. >>> print add(1, 1) 2
In the above example, we could have defined the function add() in one less line of code, as follows:
>>> def add(a, b): ... return a + b ... >>> c = add(4, 5) >>> print c 9
Thus return can "return" the result of any valid Python expression, not simply the value of a variable. If the expression you want to "return" is short, you might not want to use an extra variable (like answer above). However, as you will see later, you can sometime "return" more than one variable... Then, it may be easier to read if we use variable names instead of Python expressions.
As we mentioned at the beginning of this lesson, Reeborg has a broken compass. As a result, he only knows directly if he is facing north, or if he isn't. However, now that we know that Reeborg can remember things, we can teach him to find out which direction he is facing. For example:
def facing_south(): turn_left() turn_left() answer = facing_north() turn_left() turn_left() return answer
Let's see how this work, by examining two cases:
So, we can use our new test if we want to have Reeborg face south:
while not facing_south(): turn_left()
Write a program that has Reeborg face west, no matter what his orginal orientation is. Test it with Reeborg in various starting orientation.
Place Reeborg in an arbitrary place, facing an arbitrary direction in an empty world. Write a program that has Reeborg come back to the origin, his usual starting point, facing east. The same program should work regardless of the starting position and orientation.