[Tutor] Looping

Matt HellZFury+Python at gmail.com
Mon Apr 20 19:34:10 CEST 2009


Thank you. Func is in fact a call to an external non-python program. =]
Therefore, the loop must actually be mindlessly done. My question, however,
has been answered.
As an aside, why use range rather than xrange? I was under the impression
that xrange is a generator and therefore more memory efficient.

On Mon, Apr 20, 2009 at 1:27 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> "Matt" <HellZFury+Python at gmail.com <HellZFury%2BPython 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/
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090420/d4f3f60f/attachment-0001.htm>


More information about the Tutor mailing list