python编程生成斐波拉契数列
时间: 2024-09-20 13:00:42 浏览: 33
python3实现斐波那契数列(4种方法)
在Python中,我们可以使用递归或者循环的方式轻松地生成斐波那契数列。这里给出两种常见的方法:
**递归实现:**
```python
def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_sequence = fibonacci_recursive(n - 1)
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
n_terms = int(input("你想计算多少项斐波那契数? "))
fibonacci_list = fibonacci_recursive(n_terms)
print(fibonacci_list)
```
**迭代实现:**
```python
def fibonacci_iterative(n):
fib_sequence = [0, 1] if n >= 1 else []
for i in range(2, n+1):
fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2])
return fib_sequence
n_terms = int(input("请输入一个正整数: "))
fibonacci_list = fibonacci_iterative(n_terms)
print(fibonacci_list)
```
这两种方法都会打印出指定位置的斐波那契数列。
阅读全文