Python Forum

Full Version: UnboundLocalError: local variable 'a' referenced before assignment
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi again,
I am working on more homework. I have ideas of how to solve the problem but I am running into a bug I don't understand

def not_bad(s):
    t = s.split()
    for x in t:
        if x == "not":
            a = t.index(x)
        if x == "bad":
            b = t.index(x)
        if a < b:
            newlist = [range (a, b)]
            del t[newlist]
    print (t)




    return t


print (not_bad("this is a test"))
Basically just trying to determine if one word shows up before another in a sentence but when I run that test it gives me back:

Traceback (most recent call last):
File "/Users/leon/PycharmProjects/playpen/test5.py", line 19, in <module>
print (not_bad("this is a test"))
File "/Users/leon/PycharmProjects/playpen/test5.py", line 8, in not_bad
if a < b:
UnboundLocalError: local variable 'a' referenced before assignment

I feel like a got assigned in the if statement.

Thanks as always.
Please, use proper tags when post code, traceback, output, etc.
See BBcode help for more info.
Well what happens if x is not equal to "not" ? then a is never assigned. also b is only assigned when x is equal to "bad". only one of these two variables will be assigned at a time. So that your comparison of a < b fails. Try to assign some value to both variables. if you want to compare these to at any given point then declare them outside of your loop to store them for every iteration
def not_bad(s):
    t = s.split()
    a = 0
    b = 0
    for x in t:
        if x == "not":
            a = t.index(x)
        if x == "bad":
            b = t.index(x)
        if a < b:
            newlist = [range (a, b)]
            del t[newlist]
    print (t)
    return t
print (not_bad("this is a test"))
maybe you ment something like this? what was the task exactly?
(May-23-2018, 04:21 PM)fad3r Wrote: [ -> ]
def not_bad(s):
    t = s.split()
    for x in t:
        if x == "not":
            a = t.index(x)
        if x == "bad":
            b = t.index(x)
        if a < b:
            newlist = [range (a, b)]
            del t[newlist]
    print (t)

a only exists if x=="not". You can't reference something that doesn't exist.
As was previously mentioned, you can fix this by simply defining your variables before hand with default values.