我正在讀一本Python書,我有一個問題是需要的功能:無法確定
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.
我試過,但現在我想它應該打印16次什麼,但應該有體2語句的每個功能。我的代碼是
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")
和我得到這樣的輸出:
hello
hello
hello
hello
hjh
hjh
hjh
hjh
hjh
hjh
hjh
hjh
<function do_four at 0x1056a9840> aad
<function do_four at 0x1056a9840> aad
有人能解釋什麼,我缺少的,我怎麼能做到這一點?
P.S. - 我現在不想使用循環。我正在學習功能。
「我不想使用循環現在「 - - 太糟糕了,因爲循環是答案。 – user2357112
問題中沒有什麼說你不能使用循環,這是最簡單,最合乎邏輯的方法,只用兩行代碼來解決問題。雖然您選擇的答案中的函數只包含兩行,但它們需要添加其他所有函數才能工作 - 我認爲這違背了問題的精神(以及Python語言)。 – martineau