Fibonacci series in Python
The Fibonacci sequence has many interesting properties and appears in various areas of mathematics and science. It is often used as a simple example to introduce the concept of recursion (where a function calls itself).
Here is the first few terms of the Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
As you can see, each term is the sum of the previous two terms. For example, the third term (1) is the sum of the first two terms (0 and 1), the fourth term (2) is the sum of the second and third terms (1 and 1), and so on.
The Fibonacci series has many interesting properties and appears in various areas of mathematics and science. It is often used as a simple example to introduce the concept of recursion (where a function calls itself).
Sure! Here is a simple implementation of the Fibonacci series in Python: Program:
def fibonacci(n): if n < 0: print("Incorrect input") elif n == 1: return 0 elif n == 2: return 1 else: return fibonacci(n-1) + fibonacci(n-2) # Test the function print(fibonacci(9)) # 34
This implementation uses recursion to calculate the n-th term of the Fibonacci series. The function calls itself with the values n-1 and n-2 until it reaches the base case (n = 1 or n = 2), at which point it returns the value of the corresponding term in the series. This function will output the ninth term of the Fibonacci series (which is 34). You can easily modify it to print out the first n terms of the series by using a loop.
Comments