Python Fibonacci | Exploring the Amazing Number Patterns

Posted by

Add up of preceding numbers in a series forms a fibonacci series, individual numbers in this series are called to be python fibonacci number.

We will see an example using which you can understand the concept much easily.

0 + 1 = 1

now add

1 + 2 = 3

now add

2 + 3 = 5

In this way the series is as 0, 1, 1, 2, 3, 5 …..

You can calculate in the same way but it requires a lot of time and accuracy too be maintained so below i will explain a program in python using which you can calculate the series faster, easier and of complete accuracy.

The first step is to accept the user input for which he want the fibonacci series.

value = int(input("Enter the number of terms: "))

specify two variables and declare the values as shown below

num1, num2 = 0, 1

Yes we can specify variables in this way in python.

Now also specify the count variable

count = 0

If value is less than 0 then ask user to enter a positive number that is greater than 0

if value <= 0:
   print("Please enter a positive integer")

If user entered 1 then

elif value == 1:
   print("Fibonacci sequence upto",value,":")
   print(num1)

Now above one the process is similar for all the numbers

else:
   print("Fibonacci sequence:")
   while count < value:
       print(num1)
       nth = num1 + num2
       # Update values
       num1 = num2
       num2 = nth
       count += 1

Full Code :

value = int(input("Enter the number of terms: "))

num1, num2 = 0, 1
count = 0

if value <= 0:
   print("Please enter a positive integer")
elif value == 1:
   print("Fibonacci sequence upto",value,":")
   print(num1)
else:
   print("Fibonacci sequence:")
   while count < value:
       print(num1)
       nth = num1 + num2
       # Update values
       num1 = num2
       num2 = nth
       count += 1