Remember how, many lessons ago, we asked Reeborg to repeat some instructions?
def turn_right():
repeat(turn_left, 3)
In this lesson, we are going to see how we can define our own repeat() function.
Try the following:
>>> for letter in "Reeborg": ... print letter ... R e e b o r g
for each letter that appeared in the string Reeborg, we asked the Python interpreter to print it on a new line. If we do not want each letter to be printed on a new line, but simply spaced out on a line, we use a comma, as we mentioned before in a different situation.
>>> for letter in "Reeborg": ... print letter, ... R e e b o r g
Pretty neat! This will work with any string! Now, what if we wanted Python to count numbers instead? We could also use a for loop, together with the useful function range()
>>> for number in range(3): ... print number ... 0 1 2 >>> for number in range(14): ... print number, ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13
Feel free to try some more examples on your own!
We now have all the Python ingredients required to define our own repeat() function:
What are we waiting for?
>>> def repeat(f, n): ... for i in range(n): ... f() ... >>> def f(): ... print "It's fun!" ... >>> repeat(f, 3) It's fun! It's fun! It's fun!
Actually what we have just done is some pretty advanced Python programming! We have passed an argument to the function repeat() that was itself a function. To do this, we need to put the name of the function without the parentheses. [Look back at how we had defined turn_right() in Reeborg's world.] We also passed another argument (n) which was to be a numerical value (if range() was to give us what we wanted.) When we defined the function repeat(), Python didn't care (and didn't know!) that one of the arguments was going to be a function, and the other a number.
Note also that the variable names I chose (f, n, i) are not very descriptive. Programmers often use single letters as variables that are used within a short loop (like we had above) or a short function where we can see all at once all the places where the variable is used. However, if the variables have a special meaning, it is always preferable to give them a longer, more descriptive name. If you don't believe this, go back and try again the reading challenge at the end of lesson 10. Definitely avoiding repetitions.
So, I should perhaps have defined repeat() as follows:
def repeat(function, number_of_times): for number in range(number_of_times): function()
Go back to Reeborg's world. Choose you favourite exercise, as long as it is one where you used repeat() at least twice in your solution. Replace repeat() everywhere in your solution by a for loop. Make sure that your new solution works!