用python编出Fibonacci数列的前30项
时间: 2023-12-21 16:06:22 浏览: 49
可以使用循环或递归的方法实现Fibonacci数列的前30项,这里给出两种不同的实现方法:
1. 循环方法:
```python
# 循环方法实现Fibonacci数列的前30项
a, b = 0, 1
for i in range(30):
print(b, end=' ')
a, b = b, a + b
```
输出结果:
```
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040
```
2. 递归方法:
```python
# 递归方法实现Fibonacci数列的前30项
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(30):
print(fibonacci(i), end=' ')
```
输出结果:
```
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229
```
相关问题
用python写出Fibonacci数列前十二项
Sure, here's the code to generate the first twelve terms of the Fibonacci sequence in Python:
```
fib = [0, 1]
for i in range(2, 12):
fib.append(fib[i-1] + fib[i-2])
print(fib)
```
This will output: `[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]`
python列出斐波那契数列前四十项
可以使用递推的方法来列出斐波那契数列:
```python
fibonacci = [0, 1]
for i in range(2, 41):
fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
print(fibonacci)
```
输出结果为:
```
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296]
```
阅读全文