Python Tutorials

Python Programs

Python Print the Fibonacci Sequence


Python Print the Fibonacci Sequence

In this tutorial, we will learn how to print the Fibonacci sequence using a loop in Python. We will cover the basic loop structure to generate the Fibonacci sequence.


What is the Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence starts as 0, 1, 1, 2, 3, 5, 8, and so on.


Syntax

The syntax to print the Fibonacci sequence using a loop in Python is:

def fibonacci_loop(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b


Printing the Fibonacci sequence using a loop

We can use a loop to generate and print the Fibonacci sequence up to the n-th term.

For example,

  1. Define a function named fibonacci_loop that takes one parameter n.
  2. Initialize two variables, a and b, to 0 and 1 respectively.
  3. Use a for loop to iterate n times.
  4. In each iteration, print a and update a and b to the next numbers in the sequence.
  5. Call the function with a sample value and print the sequence.

Python Program

def fibonacci_loop(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b

# Print the first 10 terms of the Fibonacci sequence
fibonacci_loop(10)

Output

0 1 1 2 3 5 8 13 21 34