Printing Fibonacci Series Using Python3

According to Wikipedia -
In mathematics, the Fibonacci numbers form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.

So, you would have got the idea of what we are going to build.
Yes, you guessed it right. We are going to write a program that would print the fibonacci series for us.

We can achieve this using two methods:
1. Using Loops
2. Using Recursion

Using Loops:

Using For Loop:

a, b = -1, 1
for i in range(1, 10):
    a, b = b, a+b
    print(b, end=' ')

Output:




Using While Loop:

a, b = -1, 1
i = 1
while i <=10:
    a,b = b, a+b
    print(b, end=' ')
    i += 1
    

Output:


Using Recursion:

a, b = -1, 1
i = 1

def fib(n):
    global i, a, b
    if i == n:
        pass
    else:
        a, b = b, a+b
        print(b)
        i += 1
        return fib(n)
fib(10)


Output:


0 Comments