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

929 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

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."


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


What built-in types does python provide?


Write a basic program to output the lowest of 3 input numbers. (You may omit error checks on your inputs)


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–2024

Terms & Conditions|Privacy Policy