How to create a loop from this code?
<p>I have a python routine which puts PDF pages in booklet spread order. I'm trying to improve the code: there's a bit where I'm doing almost the same thing twice. When I write out the iteration, it works, but when I try to make it more general with more loops, it doesn't. The code puts two PDF pages onto a larger PDF page.</p>

<pre><code># For each side of the sheet, we must create a PDF page,
# take two source pages and place them differently, then close the page.
# If the source page number is 0, then move on without drawing.
    Sides = len(imposedOrder) / pagesPerSide
    count = 0
    for n in range(Sides):
        Quartz.CGContextBeginPage(writeContext, sheetSize)
        if imposedOrder[count]:
            page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
            Quartz.CGContextSaveGState(writeContext)
            Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, leftPage, 0, True))
            Quartz.CGContextDrawPDFPage(writeContext, page)
            Quartz.CGContextRestoreGState(writeContext)
        count += 1  

        if imposedOrder[count]:
            page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
            Quartz.CGContextSaveGState(writeContext)
            Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, rightPage, 0, True))
            Quartz.CGContextDrawPDFPage(writeContext, page)
            Quartz.CGContextRestoreGState(writeContext)
        count += 1  
        Quartz.CGContextEndPage(writeContext)
</code></pre>

<p>So the only bit that is different each time is whether we use leftPage or rightPage. </p>

<p>Here's the version that DOESN'T work:</p>

<pre><code>count = 0
for n in range(Sides):
    Quartz.CGContextBeginPage(writeContext, sheetSize)
    for nn in range (1, pagesPerSide+1):
        if nn%2 == 1:
            position = leftPage
        else:
            position = rightPage
        if imposedOrder[count]:
            page = Quartz.CGPDFDocumentGetPage(source, imposedOrder[count])
            Quartz.CGContextSaveGState(writeContext)
            Quartz.CGContextConcatCTM(writeContext, Quartz.CGPDFPageGetDrawingTransform(page, Quartz.kCGPDFMediaBox, position, 0, True))
            Quartz.CGContextDrawPDFPage(writeContext, page)
            Quartz.CGContextRestoreGState(writeContext)
        count += 1
    Quartz.CGContextEndPage(writeContext)
</code></pre>

<p>This now works. I have no idea what has changed.</p>

<p>Many thanks for looking at it.</p>

python logic