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

1428 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

How might we implement the bubble sort algorithm in Python


Why would I use dictionaries instead of a list?


How can you take a list of numbers and add 3 to every number in the list using only one line of code?


Firstly, my question is not Python related, but maths A-level related. I don't know how to change that in my profile but I would like to only tutor maths GCSE and potentially A-level. My question: Integrate sin(x)^3 over x=0 and x=pi/2.


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