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

1373 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

What are recursive functions and when should they be used?


How do you define a class in python


How could I write a program to convert Km/h to m/s in python


Write a simple Python program that asks a user to input their age and name and then return the text: "Hi my name is *NAME*, and I am *AGE* years old."


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