0

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]    
3
  • 1
    looks like you have some indention problems in the fib() function? Commented Nov 26, 2020 at 3:23
  • 2
    You're not saying that fib_called should be global in function write_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 Commented Nov 26, 2020 at 3:30
  • In write_fib function, you need to declare fib_called as global. global variables could be referenced in local function but need to declare using global when trying to assign the value Commented Nov 26, 2020 at 3:33

1 Answer 1

1

You need to add global fib_called to fib and write_fib functions.

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():
    global fib_called

    if len(gf) == 1:
        gf.append(1)
    else:
        gf.append(int(gf[-1] + gf[-2]))

    fib_called = not fib_called    


def write_fib(filename):
    global fib_called

    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]   
Sign up to request clarification or add additional context in comments.

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.