Python exercise 13 - Fibonacci

本文介绍了一个Python程序,该程序通过用户输入生成指定数量的斐波那契数列。文章提供了两种不同的实现方法,一种使用循环和列表操作,另一种使用更简洁的循环结构。这是一个优秀的练习,用于实践Python函数的使用。

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())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值