Python exercise 13 - Fibonacci

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())

猜你喜欢

转载自blog.csdn.net/Schatzke/article/details/89247122