Reputation: 329
I'm reading an exercise out of a Python book, here is what it says:
Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
Write a more general version of print_spam, called print_twice, that takes a string as a parameter and prints it twice.
Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
Heres what I wrote:
def do_twice(f, g):
f(g)
f(g)
def print_spam(s):
print (s)
do_twice(print_spam('lol'))
What is the way it is supposed to be written? I'm totally stumped on this one.
Upvotes: 2
Views: 5112
Reputation: 1
In my opinion ,according to the question from book thinkpython it had four various parts and hence each part had different code snippet in regards to the instruction provided. The second part would have print_twice as function not print_spam . Also in third part "spam" would be the argument provided not "lol". So you could try this instead. All the best.
Here is the code
def do_twice(f,g):
f(g)
f(g)
def print_twice(s):
print(s)
print(s)
do_twice(print_twice,'spam')
def do_four(do_twice,g):
do_twice(g)
do_twice(g)
Upvotes: 0
Reputation: 1
def do_twice(func, arg):
"""Runs a function twice.
func: function object
arg: argument passed to the function
"""
func(arg)
func(arg)
def print_twice(arg):
"""Prints the argument twice.
arg: anything printable
"""
print(arg)
print(arg)
def do_four(func, arg):
"""Runs a function four times.
func: function object
arg: argument passed to the function
"""
do_twice(func, arg)
do_twice(func, arg)
do_twice(print_twice, 'spam')
print('')
do_four(print_twice, 'spam')
Upvotes: 0
Reputation: 5759
If for some reason you wanted to repeat the function n amount of times, you could also write something like this...
def do_n(f,g,n):
for i in range(n):
f(g)
do_n(print_spam,'lol',5)
lol
lol
lol
lol
lol
Upvotes: 1
Reputation: 80346
Just give the string
as a second argument to do_twice
. The do_twice
functions calls the print_spam
and supplies the string
as an argument:
def do_twice(f, g):
f(g)
f(g)
def print_spam(s):
print (s)
do_twice(print_spam,'lol')
prints:
lol
lol
Upvotes: 7