Easy Tutorial
❮ Ref Math Log10 Python Comment ❯

Python Fibonacci Sequence

Python3 Examples

The Fibonacci sequence is a series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, specifically noted: the 0th term is 0, the 1st term is the first 1. Starting from the third term, each term is the sum of the previous two terms.

The Python code to implement the Fibonacci sequence is as follows:

Example (Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

# Python Fibonacci sequence implementation

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

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

# Check if the input value 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

Executing the above code will produce the following output:

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

Python3 Examples

❮ Ref Math Log10 Python Comment ❯