0

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.

3
  • 4
    q is only defined under if line[0:9]==k[0:9]:, but invariably called by your table.write(). The only explanation is that conditional must never come true. Commented Nov 2, 2015 at 18:39
  • 2
    More specifically, q is only defined if check[0]=='%'. Commented Nov 2, 2015 at 18:40
  • What @JohnGordon says is true. It's difficult for me to read 1-space indentation. Commented Nov 2, 2015 at 18:41

1 Answer 1

1

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(.).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.