Python Fibonacci Sequence Generator
Run and understand the Fibonacci sequence in Python. This interactive code example shows iterative and recursive approaches to generating Fibonacci numbers.
How it Works
The Fibonacci sequence is a series of numbers where a number is the addition of the last two numbers, starting with 0 and 1.
It is a classic computer science problem, often used to teach recursion, dynamic programming, and loop iteration.
In Python, we can generate the Fibonacci sequence efficiently using a loop (iterative approach) which avoids the stack overflow risks of deep recursion.
Source Code
This script generates the first N numbers of the Fibonacci sequence using a highly efficient while loop.
def generate_fibonacci(n):
fib_list = []
a, b = 0, 1
while len(fib_list) < n:
fib_list.append(a)
a, b = b, a + b
return fib_list
# Generate the first 10 Fibonacci numbers
terms = 10
result = generate_fibonacci(terms)
print(f"First {terms} Fibonacci numbers:")
print(result)First 10 Fibonacci numbers:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Real-world Applications
- Algorithm analysis and optimization testing
- Modeling biological growth patterns mathematically
- Technical interview preparation
Frequently Asked Questions
Is the recursive Fibonacci approach better?
In most production code cases, no. The simple recursive approach runs in O(2^n) time which is incredibly slow. The iterative loop runs in O(n) making it far superior unless memoization is used.
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.