• 0

[Python] Beginner here ... UnboundLocalError: Local var referenced b..


Question

Hi everyone,

I'm new to Python (but not to programming in general) and I'm wondering, how can I access a variable that's declared in a class, but that's modified within more than one method, without this error popping up?

Here's my code:

chain = []

def generate_sequence(start):
	while start > 1:
		chain.append(start)
		if start % 2 == 0:	#even	
			start /= 2
		elif start % 2 == 1:
			start = 3 * start + 1
	chain.append(1)

def solver():
	the_length = 0
	the_number = 1
	for i in range(1000000):
		generate_sequence(i)
		temp = len(chain)
		if temp >= the_length:
			the_length = temp
			the_number = i
		chain = []
	return the_number

And here's the error that comes up in python when I call myfile.solver():

UnboundLocalError: local variable 'chain' referenced before assignment

The error is complaining about line 20, which is temp = len(chain).

The thing is, I need to re-initialize chain to an empty list in each iteration of the 'for' loop in solver, but chain is also modified by generate_sequence. What am I missing? (I have primarily a Java background)

Thanks! :)

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

It's python's scoping rules. Since you're assigning to chain in solver(), chain becomes local to that function and hence when you try to use it before assigning, it complains. I've been bitten by the same scoping rule myself although in a different context (threads). If all that code is in a class, why aren't you accessing chain by self.chain?

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.