Python Programming Challenge #4 - Generate a Fibonacci Sequence

Free Video Tutorial and Guide

Test your Python programming skills and see if you can generate a Fibonacci sequence in this Python Programming Challenge!

Starting File

Final File

Video Transcription

Generate Fibonacci Sequence: Fibonacci sequence is a series of positive integers, where each number is the sum of the previous two. For example, it goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, etc. As the numbers increase, the ratio of any number divided by the previous number approaches the golden ratio (1.618).

Python Developer Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Given a starter list of two numbers and a target length, we're going to write a function that generates all the necessary Fibonacci numbers in the sequence. So if you call the function and pass in 15, you're saying you want a list of the first 15 Fibonacci numbers.

We already have the first two so we need to generate the next 13. The prompt starts us out with a little bit of scaffolding. We get a starter function, `find_fibo(n)`, where `n` is the argument or parameter provided for the number of Fibonacci numbers we want.

We should write it dynamically, so we'll say `fibo_needed = n - len(fibo_starter_array)`. So if it starts off as 2, `n - 2` is 13. With that number, we can loop in the range from `n` starting at 0 to `fibo_needed`, which is 13.

Every time we loop, we need a new Fibonacci number. The new value equals the current Fibonacci number plus the next value. Since we have two to start, the very first time through the array, `n` is 0, `fibo[0]` is 0, and we can add that to `fibo[1]` which is 1 to get 1 and then add that to the array.

The next time through, add that to the list. The list will be 0, 1, 1, and we'll be getting 1 and adding it to the 1 to get 2 and appending that. The next time through the list, we'll be up to 1 and 2, adding those two together and so on.

We'll append the new Fibonacci number to the `fibo` array. When the loop is over, we'll return `fibo` and that is it. Run it and there you go, it worked.

That is the solution to number four. Thanks for watching. Next up is homework solution number five.

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram