Python: Calculate Fibonacci number with 4 lines of code

Last updated on October 29, 2020 A Goodman Loading... Post a comment

The Fibonacci numbers

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)

Fibonacci numbers with 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 🙂

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x