Calculating the N-th Fibonacci Number

Category: Python Basics

Write a program that calculates the nth Fibonacci number. This program should take as input a non-negative integer and output the corresponding Fibonacci number.

Example:

Input: 5 

Output: 5

Input: 10 

Output: 55
The Fibonacci sequence is a series where each number is the sum of the two preceding ones, starting from 0 and 1. The sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(5)) # Outputs: 5
print(fibonacci(10)) # Outputs: 55

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!