Python exercise 13 - Fibonacci
Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
Discussion
Practice functions!
Code 1:
def fibonnacci():
num= int(input('Please enter how many Fibonacci numbers you want to generate:'))
fib=[]
i=0
a=b=1
if num==1:
fib=[1,]
else:
while i<num:
fib.append(b)
a,b=b,a+b
i+=1
return fib
print (fibonnacci())
Code 2:
def gen_fib():
num= int(input('Please enter how many Fibonacci numbers you want to generate:'))
i = 0
if num == 0:
fib = []
elif num == 1:
fib = [1,]
elif num == 2:
fib = [1,1]
elif num > 2:
fib = [1,1]
while i < (num - 1):
fib.append(fib[i] + fib[i-1])
i += 1
return fib
print (fibonnacci())
本文介绍了一个Python程序,该程序通过用户输入生成指定数量的斐波那契数列。文章提供了两种不同的实现方法,一种使用循环和列表操作,另一种使用更简洁的循环结构。这是一个优秀的练习,用于实践Python函数的使用。

664

被折叠的 条评论
为什么被折叠?



