Python Forum
Fibonacci sequence - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Fibonacci sequence (/thread-13066.html)



Fibonacci sequence - Darbandiman123 - Sep-26-2018

Hey i have this code which should print out fibonaccis sequence yet encounter the following error.
Error:
Traceback (most recent call last): File "C:\Users\Louis\csyr9\fibonacci.py", line 12, in <module> fibonacci() File "C:\Users\Louis\csyr9\fibonacci.py", line 5, in fibonacci while a <= 20: UnboundLocalError: local variable 'a' referenced before assignment
here is the code:
a = 1
b = 2

def fibonacci():
    while a <= 20:
        c = a+b
        d = b+c
        print (a,b,c,d)
        a = c
        b = d
fibonacci()
how do i fix this? thanks


RE: Fibonacci sequence - ichabod801 - Sep-26-2018

You need to define a and b in the function (indented under def fibonacci). Since you assign a value to a within the function, it assumes that variable is local to the function. Then it doesn't look outside the function for the value. But then on line 5 it can't find the value of a, since it hasn't been defined in the function.

See the function tutorial link in my signature below for more information.


RE: Fibonacci sequence - Darbandiman123 - Sep-26-2018

Thanks!