program to find fibonacci sequence of a number

Question:

how do i find the fibonacci sequence of a number . Here Is The code

def fib(n):
    for i in range(n):
        b = 1 
        
        b+=i
        print(b)
        
p = fib(9)

the program just returns the normal sum. how to do this in the easy way

Asked By: ganesh murthy

||

Answers:

The fibonacci sequence is built by adding the last two values of the sequence, starting with 1,1 (or 0,1 for the modern version). A recursive function does it elegantly:

def fib(n,a=1,b=1): 
    return a if n==1 else fib(n-1,b,a+b)
Answered By: Alain T.
n = 10
a, b = 0, 1
while a <= n:
    print(a)
    a, b = b, a + b
Answered By: Fat Meh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.