Python Fibonacci Number
Syntax
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
count = int(input("Enter the number of terms: "))
if count <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(count):
print(fibonacci(i))
Example
Let's find the first 10 Fibonacci numbers using Python:
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
count = 10
if count <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(count):
print(fibonacci(i))
Output
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Explanation
In the above example, we have defined a function fibonacci()
that takes in an integer n
and returns the n
th Fibonacci number. The function is implemented using a recursive approach.
Then, we have initialized a variable count
to 10. We have also added a condition that checks if the value of count
is less than or equal to zero. If it is, then it prints a message asking the user to enter a positive integer.
Finally, we have printed the first 10 Fibonacci numbers using a loop that runs from 0 to 9.
Use
The Fibonacci sequence is commonly used in mathematics, computer science, and other areas. In computer science, it is used to generate random numbers, in cryptography, and to optimize algorithms. In mathematics, it is used in number theory, combinatorics, and many other areas.
Important Points
- The Fibonacci sequence is a mathematical sequence in which each number is the sum of the two preceding numbers.
- The sequence starts with 0 and 1, so the first two numbers are 0 and 1.
- The next number in the sequence is the sum of the previous two numbers.
- The Fibonacci sequence can be implemented using a recursive approach.
- The Fibonacci sequence can be used in several areas, including computer science and mathematics.
Summary
In this tutorial, we have learned about the Fibonacci sequence and how to implement it using a recursive function in Python. We have also seen the various applications of the Fibonacci sequence in different fields.