Write a program to print the Fibonacci series in python.

The Fibonacci series is a series of Fibonacci numbers. These Fibonacci numbers have the most practical uses in the history of mathematics.

In this article, we are going to learn how to generate a Fibonacci series with a length of a given number.

Fibonacci series in python using a loop

# take input.
inp = int(input('Enter how many numbers in series you want? '))

# variables.
one, two = 0, 1
curr = 0

# return first term if inp is 1.
if inp == 1:
    print(one)
elif inp == 2:
    print(two)
# generate sequence using while loop.
else:
    print('Fibonacci series.')
    while curr < inp:
        print(one)
        temp = one + two
        one = two
        two = temp
        curr += 1

The output of the above Fibonacci series program is

$python fibonacciseries.py
Enter how many numbers in series you want? 5
Fibonacci sequence.
0
1
1
2
3

The above program starts by taking an integer input value and then runs with the initial two numbers. Below is the formula for the Nth Fibonacci number.

# Formula for Nth Fibonacci number.
F(n) = F(n-2) + F(n-1)

From the 2nd iteration in the loop, we use the above formula and generate its associated Fibonacci number. In the same loop, we print the number as well which gives us a sequence of Fibonacci numbers.

Fibonacci series in python using recursion

def print_fibonacci(inp, curr, one, two):
    if(curr == inp):
        return
    print(one)
    print_fibonacci(inp, curr+1, two, one+two)

print('Fibonacci series (length 5) using recursion:')
print_fibonacci(5, 0, 0, 1)

The output of the above program

$python fibonacciseriesrecur.py
Fibonacci series (length 5) using recursion:
0
1
1
2
3

Literally, we are using the above Nth Fibonacci number formula to generate the next Fibonacci number in the series. Hope this helps you to start learning python with the Fibonacci series using loops and recursion.

Happy learning!

Advertisements

Python hello world program

Python is a scripting language that runs using a python interpreter. The interpreter converts the program (python text file with “.py” extension) into hardware understandable format.

Let us see a simple hello world program using python language.

# helloworld.py
# Below code prints 'Hello World!' string.

print('Hello World!')

While we install the python program, it gives a set of executables in which one executable is “python” which generates an interpreter and makes it run on hardware. Below is how we use that executable.

//Output
$python helloworld.py
Hello World!

Here in the above program, we are using a function called ‘print‘ and a string ‘Hello World!’.

‘print’ is an inbuilt function that prints the string argument. A string is a sequence of characters that are in between single quotes (”), double quotes(“”) or triple quotes(”””).

Hope this python hello world program helps you to start learning python. Happy Learning!.