• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • VBA
  • About
You are here: Home / Python / Fibonacci Sequence in Python with for Loop

Fibonacci Sequence in Python with for Loop

February 24, 2022 Leave a Comment

With Python, we can easily get a Fibonacci sequence with a for loop. The Fibonacci sequence first two terms are 0 and 1, and each subsequent term is the sum of the last two terms.

def fibonacci(n):
    sequence = []
    if n == 1:
        sequence = [0]
    else:
        sequence = [0,1]
        for i in range(1, n-1):
            sequence.append(sequence[i-1] + sequence[i])
    return sequence

print(fibonacci(10))

#Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

In Python, we can generate sequences and series easily. One famous series we can create is the Fibonacci series.

The Fibonacci sequence is a sequence where every number is the sum of the last two numbers in the sequence after the first two terms.

The first ten terms of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.

We can use iteration and a for loop to create Fibonacci sequences in Python.

To generate a Fibonacci sequence of the first n terms, we just need to define a function which will create a list, loop until n-1, add the last two list elements together, then append this sum to the list.

Below is an example of a function which creates a Fibonacci sequence with a for loop in Python.

def fibonacci(n):
    sequence = []
    if n == 1:
        sequence = [0]
    else:
        sequence = [0,1]
        for i in range(1, n-1):
            sequence.append(sequence[i-1] + sequence[i])
    return sequence

print(fibonacci(10))

#Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Fibonacci Series in Python with While Loop

We can also use while loops to create Fibonacci sequences. The logic is almost identical as the example above with a for loop.

While loops loop until a condition has been satisfied. In this case, we want to loop until we have n terms in our Fibonacci sequence.

Below is an example of how to create a Fibonacci sequence using a while loop in Python.

def fibonacci(n):
    sequence = []
    if n == 1:
        sequence = [0]
    else:
        sequence = [0,1]
        count = 1
        while count + 1 < n:
            sequence.append(sequence[count-1] + sequence[count])
            count = count + 1
    return sequence

print(fibonacci(10))

#Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Fibonacci Series in Python with Recursive Function

We can also create the Fibonacci Series with recursion in Python. Recursive functions can be simple and powerful for dynamically creating or obtaining the desired result.

We can define a recursive function which will get the nth Fibonacci number.

For recursion, we need to define a base case and a recursive step.

The base case for our recursive function is when we get the first, second or third fibonacci number. These are 0, 1 and 1.

The recursive step calls our recursive function to get the previous Fibonacci number and the Fibonacci number before that, and adds them together.

Below are some examples of how to recursively find Fibonacci numbers in Python.

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

def fibonacciSequence(n):
    sequence = []
    for i in range(0,n):
        sequence.append(fibonacci(i))
    return sequence

print(fibonacciSequence(10))

#Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Hopefully this article has been useful for you to learn how to create a Fibonacci sequence of n numbers in Python with for loops.

Other Articles You'll Also Like:

  • 1.  Read Last N Lines of File in Python
  • 2.  Create Empty Tuple in Python
  • 3.  pandas ceil – Find the Ceiling of a Column Using Numpy ceil
  • 4.  Remove None From List Using Python
  • 5.  Check if Number is Between Two Numbers Using Python
  • 6.  Count Spaces in String in Python
  • 7.  Get List of Letters in Alphabet with Python
  • 8.  Calculate Sum of Dictionary Values in Python
  • 9.  Reverse a List in Python Without Reverse Function
  • 10.  Python Destroy Object – How to Delete Objects with del Keyword

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About The Programming Expert

the programming expert main image

The Programming Expert is a compilation of hundreds of code snippets to help you find solutions to your problems in Python, JavaScript, PHP, HTML, SAS, and more.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2022 · The Programming Expert · About · Privacy Policy