Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

do() do() do() 

maybe like:

3*do() 
like image 796
alwbtc Avatar asked Jan 28 '12 19:01

alwbtc


People also ask

How do you call a function more than one time?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

How do I call a function multiple times in Python?

Use the oml. index_apply function to run a Python function multiple times in Python engines spawned by the database environment. The times argument is an int that specifies the number of times to run the func function. The func argument is the function to run.

What is these term called calls the same function multiple times?

This type of function / operation is called Idempotent.

Is there a repeat function in Python?

In repeat() we give the data and give the number, how many times the data will be repeated. If we will not specify the number, it will repeat infinite times.


2 Answers

I would:

for _ in range(3):     do() 

The _ is convention for a variable whose value you don't care about.

You might also see some people write:

[do() for _ in range(3)] 

however that is slightly more expensive because it creates a list containing the return values of each invocation of do() (even if it's None), and then throws away the resulting list. I wouldn't suggest using this unless you are using the list of return values.

like image 125
Greg Hewgill Avatar answered Sep 17 '22 19:09

Greg Hewgill


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! 
like image 41
juliomalegria Avatar answered Sep 20 '22 19:09

juliomalegria