[Tutor] Looping
Alan Gauld
alan.gauld at btinternet.com
Mon Apr 20 19:27:03 CEST 2009
"Matt" <HellZFury+Python at gmail.com> wrote
> Let's say I want to run func 10 times Is there a more pythonic way to do
> it
> than this:
> for i in xrange(10):
> func()
Yes, use range() rather than xrange :-)
But more seriously, as others have pointed out, if func() is well
written then calling it ten times will have no effect over calling
it once. (Except taking up 10 times as much time!)
Its like saying
for n in range(10):
x = 42
The assignment is identical each time through the loop
In fact it's worse than that because you don't even store the
result of func() so it has no effect whatsoever on your program
outside the loop. It would be more normal to do something like:
for value in mycollection:
result = func(somevalue)
in other words apply func() to each value in a collection.
So unless your func() really takes arguments or prints time
related output or modifies global data (a bad practice) then
what you are asking doesn't make much sense.
Finally, if your function is really a program in disguise - ie it
does all its own input/output then it would make more sense
to put the loop inside the function and put the repeat count
as a parameter:
def func(repetitions):
for n in range(repetitions):
# your old func code here
And call it:
func(repetitions=10) # use keyword for clarity of purpose
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list