If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Fibonacci numbers are a sequence of numbers where each number is the sum of the two preceding ones. The sequence starts with 0 and 1, and the subsequent numbers are obtained by adding the last two numbers in the sequence. Here's how you can generate Fibonacci numbers in Python:
- Using Loop:
pythonCopy code
def fibonacci_loop(n): fib_seq = [0, 1] while len(fib_seq) < n: next_num = fib_seq[-1] + fib_seq[-2] fib_seq.append(next_num) return fib_seq # Example usage: num_terms = 10 fibonacci_sequence = fibonacci_loop(num_terms) print(f"Fibonacci Sequence ({num_terms} terms): {fibonacci_sequence}")
Output:
mathematicaCopy code
Fibonacci Sequence (10 terms): [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
In this example, the
fibonacci_loop()
function generates the Fibonacci sequence using awhile
loop. The sequence starts with[0, 1]
, and it continues to append new numbers to the sequence until it reaches the specified number of termsn
. The function returns the generated Fibonacci sequence as a list.
- Using Recursion:
pythonCopy code
def fibonacci_recursive(n): if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] else: fib_seq = fibonacci_recursive(n - 1) fib_seq.append(fib_seq[-1] + fib_seq[-2]) return fib_seq # Example usage: num_terms = 10 fibonacci_sequence = fibonacci_recursive(num_terms) print(f"Fibonacci Sequence ({num_terms} terms): {fibonacci_sequence}")
Output:
mathematicaCopy code
Fibonacci Sequence (10 terms): [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
In this example, the
fibonacci_recursive()
function generates the Fibonacci sequence using recursion. The base cases handle scenarios wheren
is less than or equal to 0, 1, or 2. Forn > 2
, the function calls itself to generate the previous terms and then appends the sum of the last two terms to the sequence.Both approaches will generate the same Fibonacci sequence with the specified number of terms. You can adjust the value of
num_terms
to generate a longer or shorter Fibonacci sequence. However, keep in mind that the recursive approach may be less efficient for large values ofnum_terms
due to the overhead of function calls.
Comments: 0