Search code examples
pythonwhile-loopiteratorlogicfibonacci

Python Fibonacci sequence- while loop is not giving me the right result. I have tried changing the iterator but to no avail?


    num1 = 0
    num2 = 1
    find = 2
    fib_num = 0

    while find <= N:
        fib_num = num1 + num2
        num1 = num2
        num2 = fib_num
        find = find + 1
    print(find)


fibFind(7)

I have been having issues with the Fibonacci sequence- I have searched for the 7th number- the result should be 13. Where am I going wrong with the logic?

Thanks in advance for answer and explanation.


Solution

  • You need to print fib_num, not find.

    def fibFind(N):
        num1 = 0
        num2 = 1
        find = 2
        fib_num = 0
    
        while find <= N:
            fib_num = num1 + num2
            num1 = num2
            num2 = fib_num
            find = find + 1
    
        print(fib_num)
    
    
    fibFind(7)
    

    Better yet, return the fibonacci number from the function after the computation is done.

    def fibFind(N):
        num1 = 0
        num2 = 1
        find = 2
        fib_num = 0
    
        while find <= N:
            fib_num = num1 + num2
            num1 = num2
            num2 = fib_num
            find = find + 1
    
        return fib_num
    
    
    print(fibFind(7))