I have this code regarding the fibonacci sequence and wriing an n number of fibonacci numbers to a file. I was wondering why I am getting an unbound local error here. It says I am referencing the variable fib_called before assignment.
fib_called = False
def global_fib(n, filename):
global gf
gf = load_fib(filename)
i = 0
write_fib(filename)
while i < n:
fib()
write_fib(filename)
i += 1
return return_fib()
import os
def fib():
if len(gf) == 1:
gf.append(1)
else:
gf.append(int(gf[-1] + gf[-2]))
fib_called = not fib_called
def write_fib(filename):
if fib_called == True:
filename.open('w')
filename.write(str(gf[-1]) + ' ')
fib_called = not fib_called
def load_fib(filename):
if os.path.exists(filename):
filename.open('r')
content == filename.read()
return list(content)
else:
f = open("newfile",'w')
f.write('0' + ' ')
return [0]
def return_fib():
return gf[-1]
fib_calledshould be global in functionwrite_fib. That makes it a local variable with the same name. A local variable in which you read from before you assign it. Hence the error