In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
The sequence Fn of Fibonacci numbers is defined by the recurrence relation:
Fn = Fn-1 + Fn
with seed values F1 = 1 F2 = 1
For more information on Fibonacci Numbers see Wikipedia. We want to write a program that asks the user how many Fibonacci numbers they want to generate, put them in a list and then output the list. Keep in mind there are 3 special cases we need to handle.
Number to Fibonacci numbers to generate | Result |
---|---|
0 | [] |
1 | [1] |
2 | [1,1] |
One last reminder is we user the list.append(value) to add value to list. See Adding and removing list elements in Section 3.2. The output of the program should look like this.
How many Fibonacci numbers would you like to generate? 5
The first 5 Fibonacci numbers are [1, 1, 2, 3, 5].
Python Program:
# Fibonacci number generator function
def fibonacci_numbers(num):
fib_list = [1, 1]
if num == 0:
return []
elif num == 1:
return fib_list[0:1]
elif num == 2:
return fib_list
else:
for i in range(2, num):
next_fibonacci = fib_list[i-1] + fib_list[i-2]
fib_list.append(next_fibonacci)
return fib_list
# Main Driver Function
if __name__ == "__main__":
num = int(input("How many Fibonacci numbers would you like to generate? "))
fibonacci_list = fibonacci_numbers(num)
print("The first {0} Fibonacci numbers are : {1}".format(num, fibonacci_list))
Output:
Thumbs Up Please !!!
Get Answers For Free
Most questions answered within 1 hours.