Write a recursive function that takes any integer n and prints the nth Fibonacci number.

A recursive function is a function that can call itself. Fibonacci numbers are defined:F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1, giving the sequence 0, 1, 1, 2, 3, 5, 8, 13, ... which you're probably familiar with.Here's how we can write that in python:def fib(n): if n <= 0: # The base and invalid case return 0 elif n == 1: # Another base case return 1 else: # The recursive definition return fib(n-1) + fib(n-2) print(fib(6)) # Prints 8 There are a few things to consider. Why do we we need the 'return 0' and 'return 1' statements? What's the invalid case? Is this the best way to find the nth Fibonacci number?

Answered by Andrew G. Python tutor

1283 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

How do I use format python code?


Create a python code to sum the number from 1 to 10.


Write a program that takes a value x and then outputs x Fibonnaci numbers. E.g. if x=6 output would be 1 1 2 3 5 8


Make a program that asks the user for a series of numbers until they either want to output the average or quit the program.


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences