Home » PythonPi Bonus Lessons » PythonPi Bonus: Fibonacci

PythonPi Bonus: Fibonacci

When carrying out the bonus lessons, you should have already completed the 8 week introductory course and submitted all your coursework to maximum possible standard.

Today we will be learning about the vast mathematical functions of Python starting with Fibonacci numbers. Fibonacci is a sequence of numbers that add together with the previous one in the sequence to create the next one. For example:

0,1,1,2,3,5,8,13,21,34,55

That is an initial Fibonacci sequence starting from Zero. In Python we can write a very easy function to do this, where we define the number in the sequence we want, and Python will return us the number in that section of the sequence. The code is fairly simple to write as well.

First of all we will write a function that allows us to ask it for the fibonacci number we require.

def fibonacci(n):
if n == 0:
return  0;
elif n == 1:
return 1;
else:
return (fibonacci(n-1)+(fibonacci(n-2))

HINT: input_var returns a string, you’d want an int to pass to the method above.

Call this function and then insert the number you would like to find in the fibonacci sequence. You can do this in the Virtual Programming Lab in Classroom and earn an extra badge for doing more coding 😀


Leave a comment

Your email address will not be published. Required fields are marked *