MikeKusold
MikeKusold

Reputation: 1632

Decrement a variable in an incrementing for loop

In my python script, I am itterating through a list (headerRow) starting at index 9. I want to check to see if it is already in the database, and if not then add it to a database with an auto-incementing primary key. I then want to send it through the loop again to retrieve it's primary key.

for i in range (9, len(headerRow)):
    # Attempt to retrieve an entry's corresponding primary key.
    row = cursor.fetchone()
    print i

    if row == None: # New Entry
        # Add entry to database
        print "New Entry Added!"
        i -= 1 # This was done so that it reiterates through and can get the PK next time.
        print i

    else: # Entry already exists
        print "Existing Entry"
        qpID = row[0]
        # ...

Here is the output of my script:

9
New Question Added!
8
10
New Question Added!
9
11

As you can see, my issue is that range() doesn't care what the existing value of i is. What is the preferred python way to do what I'm trying to do?

Thanks in advance,

Mike

Upvotes: 1

Views: 9515

Answers (2)

Mattias Nilsson
Mattias Nilsson

Reputation: 3757

My great distaste for manually changing index variables makes me want to comment on this... :) How about just changing it to do both things in the same iteration? Code looks a little strange, but you get the idea.

for i in range (9, len(headerRow)):
    # Attempt to retrieve an entry's corresponding primary key.
    row = cursor.fetchone()
    print i

    if row == None: # New Entry
        # Add entry to database
        print "New Entry Added!"
        row = cursor.fetchone() # re-fetch to get the PK

    # Entry will exist now
    print "Getting Existing Entry"

    qpID = row[0]
    # ...

And to try to explain why decrementing the "i" doesn't work:

The for loop doesn't really increment the variable. It simply picks the next value from the sequence you gave it (generated by the range function). So if the secquence is [9,10,11,12] it will pick those, in order. The variable "i" will get the next value and the previous will be discarded. No increment or decrement will affect this.

Upvotes: 1

Patrick
Patrick

Reputation: 1148

Why not use a while loop?

i=9
while (i<len(headerRow)):
    # Attempt to retrieve an entry's corresponding primary key.
    row = cursor.fetchone()

    if row == None: # New Entry
        # Add entry to database
        print "New Entry Added!"
    else: # Entry already exists
        print "Existing Entry"
        qpID = row[0]
        i += 1
        # ...

Upvotes: 6

Related Questions