简体   繁体   English

如何调用 function 和 arguments 在 ZA7F5F35426B9237411FCZ2317B 中使用另一个 function

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

Trying to learn Python from the Think Python book and at the section about recursive functions.尝试从Think Python书和关于递归函数的部分学习 Python。 An exercise there made me wonder how to call a function with arguments using another function generically.那里的一个练习让我想知道如何使用另一个 function 来调用 function 和 arguments。

The answer to the exercise itself is already available in another thread , but all solutions involve modifying the third function do_n() to add additional arguments that will match the second function print_n()练习本身的答案已在另一个线程中提供,但所有解决方案都涉及修改第三个 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 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?

Thanks!谢谢!

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...? 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...?

I don't know where it would be useful to have the arguments entered by the user, but since you ask for it:我不知道让用户输入 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