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?

AG
Answered by Andrew G. Python tutor

1366 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What can be used to iterate through a list in python?


Create a program that generates prime numbers between two integer boundareis


Using the shared code editor, write a recursive function for calculating a factorial of an input parameter.


Give an example of a FOR loop


We're here to help

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

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences