I'm a beginner with python, and I'm trying to make a script that will print the fibonacci sequence as a list, or a specified number in the sequence based on a given number. This probably sounds confusing, so let me show you guys the code, and then explain.
number = 1
last = 0
before_last = 0
def Fibonacci(number, last, before_last):
Question = raw_input('Would you like a List or the Number: ')
X = raw_input('Give a number: ')
print number
if Question == "List":
for counter in range(0, int(X) - 1):
before_last = last
last = number
number = before_last + last
print number
if Question == "Number":
for counter in range (int(X) - 2, int(X) - 1):
before_last = last
last = number
number = before_last + last
print number
Fibonacci(number, last, before_last)
Basically, you choose list or number, and you give the code your number. The number is taken, and used in the range. However, with the singular number, it will only print the number one. Why is this, and how do i fix it, so that if I gave the code the number 10 as input, it would print the 10th number in the Fibonacci sequence? An explanation and how to fix it would be quite helpful, and if any of you can give helpful advice, that would be amazing.
You can use a List to keep track of all numbers in the sequence, and then print whichever number you want. Try this:
number = 1
last = 0
before_last = 0
def Fibonacci(number, last, before_last):
Question = raw_input('Would you like a List or the Number: ')
l=[1]
X = raw_input('Give a number: ')
if Question == "List":
print number
for counter in range(0, int(X) - 1):
before_last = last
last = number
number = before_last + last
print number
if Question == "Number":
for counter in range (0, int(X)):
before_last = last
last = number
number = before_last + last
l.append(number)
print l[int(X)-1]
Fibonacci(number, last, before_last)
Output:
#Would you like a List or the Number: List
#Give a number: 6
#1
#1
#2
#3
#5
#8
#Would you like a List or the Number: Number
#Give a number: 6
#8