Sam V
Sam V

Reputation: 343

What is causing Python not to recognize a variable defined in a for loop?

I was hoping that someone could explain to me what I'm doing to cause a variable defined in a for loop to not be recognized when I attempt to call it later on. Basically, I've got a large list of frequencies that each have a bunch of possible molecules matches listed under them, and I marked the correct molecule with a '%' when I identified it to come back to later. Now I'm trying to pull those frequency-molecule matches out for something else, and my method was this:

frequencies = [17.987463, ...etc]  # large list
for k in frequencies:
    g = open('list', 'r')
    for line in g:
        if line[0:9] == k[0:9]:
            # if the entry in the list matches the observed frequency
            for _ in range(25):
                check = str(g.next())  # check all lines under it for a % symbol
                if check[0] == '%':
                    q = check.split('\t')[-1]
                    break
                    # if you find it, save the last entry and stop the for loop. Continue until you find it.
                else:
                    continue
        else:
            continue

    table.write(str(q))
    table.write(str(k))

But this says "UnboundLocalError: local variable 'q' referenced before assignment".

If I'd defined q inside a function I would understand, but I'm confused why it's saying this because you can write something like

for i in range(5):
 x=i**2

print x

and get 16, so we know that variables defined in for loops will exist outside of them.

I thought that whatever the problem was, it could be fixed by making a global variable so I added in a line so that middle part read:

if check[0]=='%':
 global q
 q=check.split('\t')[-1]

but then it says "NameError: global name 'q' is not defined". Could someone please explain what I'm doing wrong? Thank you.

Upvotes: 0

Views: 98

Answers (1)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

The assignment is never executed.

This will never evaluate to true:

 if line[0:9]==k[0:9]: 

g.read() will yield a str object, while the elements of frequencies are floats.

You probably want something like:

if line[0:9]==str(k)[0:9]

This will convert the float k to a str and then trim it to 9 characters, including the separator(.).

Upvotes: 1

Related Questions