Python Tutorial (33) - Example: Fibonacci sequence

Time: Column:Python views:251

Fibonacci Sequence in Python

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. Specifically, the 0th term is 0, and the 1st term is the first 1. From the third term onward, each term equals the sum of the two previous terms.

Here is the Python code to implement the Fibonacci sequence:

Example

# Python implementation of Fibonacci sequence

# Get user input
nterms = int(input("How many terms do you need? "))

# First and second terms
n1, n2 = 0, 1
count = 2

# Check if the input is valid
if nterms <= 0:
    print("Please enter a positive integer.")
elif nterms == 1:
    print("Fibonacci sequence:")
    print(n1)
else:
    print("Fibonacci sequence:")
    print(n1, ",", n2, end=" , ")
    while count < nterms:
        nth = n1 + n2
        print(nth, end=" , ")
        # Update values
        n1, n2 = n2, nth
        count += 1

Example Output:

How many terms do you need? 10
Fibonacci sequence:
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,

In this example, the program calculates the Fibonacci sequence up to the number of terms specified by the user. It initializes the first two terms and uses a while loop to compute and print the subsequent terms.