Python Fibonacci series with recursion and loop

Python

In this post, We will learn a Program of Python Fibonacci series with recursion and loop and Fibonacci series using the list.

1. Fibonacci sequence using recursion


In this example, we have defined a function recur_fibonacci_sequence to find the Fibonacci series recursively. We are taking input numbers from users.

Using the for loop from 0 to the inputted number we are calling the custom define function to find the Fibonacci series recursively.

Python Program

def recur_fibonacci_sequence(num):
	if num<=1:
		return num
	else:
		return(recur_fibonacci_sequence(num-1) + recur_fibonacci_sequence(num-2))

num = int(input('Enter a number postive number : '))

for n in range(num):
       print(recur_fibonacci_sequence(n),end=" ")

Output

Enter a number postive number : 12
0 1 1 2 3 5 8 13 21 34 55 89 

2.Fibonacci sequence using list


In this example, we are finding the Fibonacci sequence using the list. We are taking a number input from the user using the input() function and int() function to convert enter number to int.

Using the for loop starting from 2 till the number to display the Fibonacci sequence.

Program Example

list_fibonacci = [0, 1]

num = int(input('Please enter postive number: '))

for num in range(2,num):
    list_fibonacci.append(list_fibonacci[num-1]+list_fibonacci[num-2])

print(list_fibonacci)

output

Please enter postive number: 11
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

3. Fibonacci Series in Python using for loop


In this example, we are finding Fibonacci series using for loop without recursion. The taking input of number using python input() function and converting it into an integer by using int() function.

Next checking If the number is less than zero and printing a message on the console using the print() function.

Next, we are using for loop start from 2 till the number to find the Fibonacci sequence

num = int(input("Please enter number to find fibbonic sequence :"))
first_num =0   #first number of sequnce
second_num =1   #second number of sequnce
                                        
if num<=0:
    print(F"The sequence of number is : {first_num}")
else:
    print(first_num,second_num,end=" ")
    for x in range(2,num):
        next_num = first_num+second_num                         
        print(next_num,end=" ")
        first_num = second_num
        second_num=next_num

Output

Please enter number to find fibbonic sequence :13
0 1 1 2 3 5 8 13 21 34 55 89 144