Python: Calculate Fibonacci number with 4 lines of code

Last updated on February 23, 2022 A Goodman Loading... Post a comment

The Fibonacci sequence looks like this:

F(0) = 1
F(1) = 1
F(2) = F(0) + F(1)
F(3) = F(2) + F(1)
F(n) = F(n-1) + F(n-2)

Calculating Fibonacci numbers in Python

Reminder: Python accepts function recursion, which means a defined function can call itself.

With only 4 lines of Python code, we can write a program that calculates the n-th Fibonacci number. Here is it:

def fib(n):
  if(n < 2):
    return 1
  return fib(n -1) + fib(n -2)

Try it:

print(fib(5)) # Output: 8
print(fib(10)) # Output: 89
print(fib(30)) # Output: 1346269

That’s it. Happy programming with Python.

Further reading:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles