[英]Python 3: How to call function from another file and pass arguments to that 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.