user325923 user325923 - 10 months ago 24
Python Question

Unable to define desired function

I was reading a python book and I got a question which is:


Define a new function called "do_four" that takes a function object
and a value and calls the function four times, passing the value as a
parameter. There should be only two statements in the body of this
function, not four.


I tried but now I want that it should print 16 times anything but there should be 2 statement in body of each function. My code is

def hello1(a, g):
a(g)
a(g)

def hello2(ar):
print (ar)
print (ar)

hello1(hello2, "hello")
print("")

def do_four(a, g):
hello1(a, g)
hello1(a, g)

do_four(hello2, "hjh")
print("")

def hello3(a, g):
print (a, g)
print (a, g)

hello3(do_four, "aad")


and I am getting this output:

hello
hello
hello
hello

hjh
hjh
hjh
hjh
hjh
hjh
hjh
hjh

<function do_four at 0x1056a9840> aad
<function do_four at 0x1056a9840> aad


Can someone explain what I am missing and how I can do this?

P.S. - I don't want to use loop now. I am learning functions.

Answer
def hello1(a, g):
    a(g)
    a(g)

def hello2(ar):
    print (ar)
    print (ar)

hello1(hello2, "hello")
print("")

def do_four(a, g):
    hello1(a, g)
    hello1(a, g)

do_four(hello2, "hjh")
print("")

def hello3(a, g):
    print (a(hello2, g))
    print (a(hello2, g))

hello3(do_four, "aad")

output:

hello hello hello hello

hjh hjh hjh hjh hjh hjh hjh hjh

aad aad aad aad aad aad aad aad None aad aad aad aad aad aad aad aad None