April 3, 2012

Fibonacci code in Python language

Code to output Fibonacci number in Python


Fibonacci code can be written in Python language very easily and efficiently.
It can be done recursively or non-recursively. I have provided non recursive examples in other post, hence this  Fibonacci code example is written in recursive manner.

Code:
def  fib:
       if (n==0):
            return 0
       elif (n==1):
             return 1
       else:
             return (fib(n-2)+fib(n-1))

print fib(0)
print fib(5)

First, a function or procedure is define on first line. Since python identifies code blocks using indentation, all codes must be properly indented.

Run this code in any Python compiler (one online compiler is http://www.codepad.org ) and see the result.

If you find any problem regarding understanding the recursive code, please see other non-recursive examples or put a comment. I will answer as elaborately as possible.