Reputation: 3
The goal is to pass a function and a number as arguments to another function, which then recursively calls the passed function n times. I implemented this two ways. This version works as expected, printing Hello World
3 times:
def do_n(fx, n):
if n <= 0:
return
else:
print(fx)
do_n(fx, n-1)
def return_greeting():
return "Hello World"
do_n(return_greeting(), 3)
This version does not work. It prints Hello World
only once, and then seems to lose the called function after the first time through:
def do_n(fx, n):
if n <= 0:
return
else:
fx
do_n(fx, n-1)
def print_greeting():
print("Hello World")
do_n(print_greeting(), 3)
Can someone explain why the second version does not result in print_greeting
being called 3 times and printing Hello World
3 times to the screen?
Upvotes: 0
Views: 242
Reputation: 4318
In the first version, you are passing Hello World
string to do_n function and printing n times that's why it just prints n times (actually you are not calling the function).
In the second version, you have the string but you are just declaring it..If you want to make this function really call, you have to change your code as:
def do_n(fx, n):
if n <= 0:
return
else:
fx()
do_n(fx, n-1)
def return_greeting():
print "Hello World"
do_n(return_greeting, 3)
Upvotes: 0
Reputation: 308196
The statement fx
doesn't do anything. I think you meant to say fx()
to actually call the function.
Upvotes: 1
Reputation: 44132
The second version doesn't call print_greeting
three times -- actually, neither version does.
You call print_greeting
exactly once, in the last line of each code snippet. In that line, you call it, and it returns the string, and you just pass the string into your do_n
function.
You can make two changes to your second snippet to make it do what you think it should be doing:
First, dont call print_greeting
in the last line. It should look like this:
do_n(print_greeting, 3)
That way, you pass the actual function print_greeting
into your do_n function.
Second, call the passed function (now called fx
) like this:
fx()
The parentheses here mean "call this function".
The whole snippet should look like this:
def do_n(fx, n):
if n <= 0:
return
else:
fx()
do_n(fx, n-1)
def print_greeting():
print("Hello World")
do_n(print_greeting, 3)
Upvotes: 2