Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading