Fibonacci Series using Python Programming

Introduction

Here we will see fibonacci series using Python programming. A fibonacci series is a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. For example, the series is – 1, 1, 2, 3, 5, 8, etc.

By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

The Fibonacci sequence is named after Italian mathematician Leonardo of Pisa, known as Fibonacci.

Prerequisites

In this example we will use Python 3.6 and you must have knowledge on Python language to implement.

Example with Source Code

We will write function to print fibonacci series using Python programming.

The below function prints fibonacci series upto n, where n is an integer value passed as an argument to the function:

def fib(n):
     a, b = 0, 1
     while a < n:
         print(a, end=' ')
         a, b = b, a+b
     print()

In the above function definition:

The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented.

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the second line from the last this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

The while loop executes as long as the condition (here: a < n) remains true.

The body of the loop is indented: indentation is Python’s way of grouping statements. Note that each line within a basic block must be indented by the same amount.

The print() function writes the value of the argument(s) it is given.

Usage

fib(100)

Output

0 1 1 2 3 5 8 13 21 34 55 89

We write another function that will return the fibonacci series instead of just printing:

def fib(n):
     result = []
     a, b = 0, 1
     while a < n:
         result.append(a)
         a, b = b, a+b
     return result

In the above function:

The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

The statement result.append(a) calls a method of the list object result. The method append() shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is equivalent to result = result + [a], but more efficient.

Usage

f = fib(100)

Then you need to write the result of f.

Thanks for reading.

Leave a Reply

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