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)
Question
dt
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:
And here's the error that comes up in python when I call myfile.solver():
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