簡體   English   中英

如何調用 function 和 arguments 在 ZA7F5F35426B9237411FCZ2317B 中使用另一個 function

[英]How to call a function with arguments using another function in Python

嘗試從Think Python書和關於遞歸函數的部分學習 Python。 那里的一個練習讓我想知道如何使用另一個 function 來調用 function 和 arguments。

練習本身的答案已在另一個線程中提供,但所有解決方案都涉及修改第三個 function do_n()以添加與第二個 ZC1C425268E68385D1AB5074C17A94F1 匹配的額外print_n()

def countdown(n): # FIRST FUNCTION
    if n <= 0:
        print("blastoise")
    else:
        print(n)
        countdown(n-1)

def print_n(s, n): # SECOND FUNCTION
    if n <=0:
        return
    print(s)
    print_n(s, n-1)

def do_n(f, s, n): # THIRD FUNCTION
    if n <= 0:
        return
    f(s, n)
    do_n(f, s, n-1)

How do you write the third function so that it is generic and works to call either the first function or second function or any other function by prompting you to enter the arguments for the called function instead of the solution above?

謝謝!

How do you write the third function so that it is generic and works to call either first function or second function or any other function by prompting you to enter the arguments...?

我不知道讓用戶輸入 arguments 有什么用處,但既然你要求它:

def do_in(f, n):                        # prompt to enter arguments, call f n times
    try: a = eval(input('comma separated arguments: '))
    except SyntaxError: a = ()          # you may want more sophisticated error checks
    if not isinstance(a, tuple): a = a, # make single argument iterable
    for _ in range(n): f(*a)            # unpack arguments with starred expression

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM