fibonacci numbers in python

Here's a simple Python function that uses recursion to calculate the nth Fibonacci number:

main.py
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)
107 chars
6 lines

To use this function, simply call fibonacci(n) with the number n representing the index of the desired Fibonacci number. For example, to calculate the 10th Fibonacci number:

main.py
fibonacci(10) # Output: 55
27 chars
2 lines

Keep in mind that this implementation has exponential time complexity, meaning it's not very efficient for large values of n. There are more optimized algorithms for calculating Fibonacci numbers, such as using a loop or memoization, but this recursive implementation is the most straightforward to understand.

gistlibby LogSnag