I am playing around with Python on the DNA problem. I realize there are some string methods that might make this problem easier but my gut instinct was to try and make an "search function" from scratch. I think i have basically done that but I am getting a weird error that I a)cant eliminate b)dont really understand.

UnboundLocalError: local variable 'sbox' referenced before assignment

I normally would totally understand that error except in this case 'sbox' is a function I defined and wrote myself, not a variable at all. I feel like i am missing something super basic here but i am kind of pulling my hair out over this.

Here is the code *one note about this code. I pulled this code out and dropped it into a separate file to try and isolate and fix problems with my search and count functions. This is why i am hard coding in opening "1.txt" instead of pulling it in from a command line argument. I generally think that when this little chunk is finished it should function independent of the rest of the assignment. IE it should read the string in "1.txt" and update a dictionary with the various STR counts. And nothing else. Due to my current hurdle i haven't been able to assess the rest of the code yet.

import csv

def main():

    perp = open("1.txt","r")
    theperp =perp.read()

    #creates a dictionary of STRs to tally for the perp

    #initializes indexes for strs of various sizes

    #runs function sbox to update the perps dictionary

    #defines a function that searches a string for various letter patterns
    #x is the starting position of the substring
    #y is the ending position of the substrsing
    #z is the total size of the substring
    #theperp is the string passed to the fucntion to search
    #strs1 is the dictionary to be updated
    def sbox(x,y,z,theperp,strs1):
        while b<=len(theperp):
            if strs1[sbox4] == None:
                if compare>theperp[sbox4]:

    #function to update strs dictionary
    #box is the value of the sbox passed to the function
    #dic is the dictionary to be updated.  in this case always strs
    #x is the initial index of the search box
    #y is the ending index of the search box
    #z is the amount the search box should index forward to examine the next potential STR
    def count_str(box,dic,x,y,z):

        while box==dic[box]:
            count +=1
        if count>dic[box]:
            return count


Thanks so much for the help, Rob

1 Answer 1


When program encounters the first occurence of sbox it doesn't know what it is because it has not been defined. The message says "local variable" because of how namespaces work inside functions (in this case main). The function needs to be defined globally (ie outside main) or before sbox is used (inside main).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .