Open dimwael opened 2 days ago
To create a Python function to calculate the Fibonacci sequence, we can use recursion or iteration. Here's an example using recursion:
def fibonacci(n):
"""
Calculate the nth Fibonacci number.
Args:
n (int): The position of the desired Fibonacci number.
Returns:
int: The nth Fibonacci number.
"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
To use this function, simply call it with the desired position n
:
print(fibonacci(10)) # Output: 55
This will print the 10th Fibonacci number, which is 55.
Alternatively, here's an iterative version:
def fibonacci(n):
"""
Calculate the nth Fibonacci number.
Args:
n (int): The position of the desired Fibonacci number.
Returns:
int: The nth Fibonacci number.
"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for i in range(n-1):
a, b = b, a + b
return b
This iterative approach is generally more efficient than the recursive version for larger values of n
.
How to create a python function to calculate fibonacci