Practice Python

Beginner Python exercises

25 July 2014

Fibonacci Solutions

Exercise 13

Write a program that asks the user how many Fibonacci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate.(Hint: The Fibonacci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)

Sample solution

There are so many ways that you can use functions to generate Fibonacci numbers. Here is one user-submitted solution:

And another:

This solution is using what is called the “iterative” method of computing Fibonacci numbers. This means you use some kind of loop to keep adding numbers together to get the next number.

An alternative way of computing Fibonacci numbers is to use recursion, or calling the same function over and over in a special way, to compute the Fibonacci numbers. We will talk about this in a future exercise.


comments powered by Disqus