The Fibonacci sequence is a well-known pattern of numbers that has been used in mathematics since antiquity. This series is characterised by each number being the sum of the two numbers prior, which always begin with 0 and 1. To generate a Fibonacci series of any length, simply add the two numbers preceding it together to find the next number. For example, to create a sequence of 6 numbers (0, 1, 1, 2, 3, 5), the process would be 0 + 1 = 1; 1 + 1 = 2; 1 + 2 = 3; 2 + 3 = 5. This sequence of numbers is known as the Fibonacci series.
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
Find the Nth Fibonacci Number with our Program! Our program starts by taking an integer input value and then runs a loop with the initial two numbers. We use the formula F(n) = F(n-2) + F(n-1) to generate the associated Fibonacci number from the second iteration of the loop. The result of this process is a sequence of Fibonacci numbers that can be printed out. Try it out today to see the Nth Fibonacci number!
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
This program prints out the first 5 numbers of the Fibonacci sequence using recursion. The Fibonacci sequence is a series of numbers where each number is the sum of the previous two numbers. The first two numbers in the sequence are 0 and 1. The program takes in three parameters: the desired length of the Fibonacci sequence (inp), the current number in the sequence (curr), and the last two Fibonacci numbers (one and two). The program prints the first number, then calls itself with an incremented curr and the two last numbers, one and two. This process continues until the desired length of the sequence is reached.
I wish you all the best as you begin your journey studying Python, with the Fibonacci sequence using loops and recursion. Enjoy your learning!