beginner, idiomatic python
Neil Cerutti
horpner at yahoo.com
Mon Aug 27 14:20:33 EDT 2007
On 2007-08-27, bambam <david at asdf.asdf> wrote:
> Thank you, I have been through the tutorial several times, I
> guess I'm just not smart enough. Perhaps I have been led astray
> by what I read here?
>
> My code started like this:
>
> for i in range(self.parent.GetPageCount()):
>
> I was asked:
>
>> Does page count change? i.e. is it necessary to retrieve it in
>> every loop
>
> Is self.parent.GetPageCount() 'retrieved every loop'?
No. The question seems to imply that if you wish it to be
retrieved every loop you must change the code to something else.
i = 0
while i < self.parent.GetPageCount():
# do stuff
i += 1
I find that kind of while loop clunky. Since Python is
hard-headed about not providing a structured looping construct,
you may feel the need to compose your own special-purpose
iterator or generator instead.
def pageCountGenerator(document):
i = 0
while i < document.GetPageCount():
yield i
i += 1
It can be used like this:
for i in pageCountGenerator(self.parent):
# do stuff
That way you get the happy syntax of a for loop, with the
additional safety of checking the page count each iteration.
This sort of suggests a direct solution:
for i in xrange(self.parent.GetPageCount()):
if i >= self.parent.GetPageCount():
break
# do stuff
At least that way you're spared the manual manipulation of i.
--
Neil Cerutti
More information about the Python-list
mailing list