# Python: Calculate Fibonacci number with 4 lines of code

( 50 Articles)

**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:**

- VS Code: How to comment out a block of Python code
- Using the isinstance() function in Python 3
- How to Install Python Libraries in Google Colab
- Tensorflow 2 – How to Reverse a Tensor
- Tensorflow 2 – How to Print only the Value of a Tensor

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

Subscribe

0 Comments