How do I call a function twice or more times consecutively?

后端 未结 9 1833
借酒劲吻你
借酒劲吻你 2020-12-05 00:02

Is there a short way to call a function twice or more consecutively in Python? For example:

do()
do()
do()

maybe like:

3*do         


        
9条回答
  •  天命终不由人
    2020-12-05 00:43

    You could define a function that repeats the passed function N times.

    def repeat_fun(times, f):
        for i in range(times): f()
    

    If you want to make it even more flexible, you can even pass arguments to the function being repeated:

    def repeat_fun(times, f, *args):
        for i in range(times): f(*args)
    

    Usage:

    >>> def do():
    ...   print 'Doing'
    ... 
    >>> def say(s):
    ...   print s
    ... 
    >>> repeat_fun(3, do)
    Doing
    Doing
    Doing
    >>> repeat_fun(4, say, 'Hello!')
    Hello!
    Hello!
    Hello!
    Hello!
    

提交回复
热议问题