0

I have the following code but Python keeps saying "local variable 'a' referenced before assignment"

def inter(X,Y):
    if pertenece(cabeza(X),Y):
        a = lista(cabeza(X),inter(cola(X),Y))
    elif vacia(cola(X)): return a
    else: inter(cola(X),Y)

I have no idea why I'm getting this error since I have defined 'a' before referencing it. Please help.

The functions 'pertenece', 'cabeza', 'cola', 'vacia' and 'lista' where all previously defined and have no issue.

5
  • 3
    return a will only happen if pertenece(cabeza(X),Y) is False, but a will only be set if pertenece(cabeza(X),Y) is True. What do you want a to be when pertenece(cabeza(X),Y) is False? Commented Oct 31, 2020 at 14:43
  • It wouldn't enter elif condition when it has entered if condition. Commented Oct 31, 2020 at 14:43
  • Does this answer your question? Python 3: UnboundLocalError: local variable referenced before assignment Commented Oct 31, 2020 at 14:51
  • @Carcigenicate , is there a way to sort of 'bring the value of 'a'? Something like assigning a permanent value for 'a'? Commented Oct 31, 2020 at 14:54
  • @RandomUser Set it before the if. Commented Oct 31, 2020 at 14:55

2 Answers 2

1

I think this is because you're initializing var a in an if clause, and refrencing it in another if clause, so considering the condition it may or may not be initialized befored it is referenced in if clause. Can you try to initialize a within the function body before your first if clause, to a empty or null value. Maybe that could help.

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

Comments

0

You have only defined a in the first conditional statement. If the code never goes through that condition, then a will never be defined. You would have to assign some default value for a before the conditional statements in order to prevent the return statement from throwing an error at you.

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.