I am reading a textbook and I have no idea why is this code compiling differently on my compiler than what it says in the book.
def fibs(number):
result = [0, 1]
for i in range(number-2):
result.append(result[-2] + result[-1])
return result
So this:
fibs(10) should give me [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] but for some reason I get [0, 1, 1] for every number that I pass in to the function.
Any ideas?
The code in your post isn't valid Python. Since your code was able to run, it's probably actually like this:
def fibs(number):
result = [0, 1]
for i in range(number-2):
result.append(result[-2] + result[-1])
return result
Your return result is indented such that it's inside the for loop, instead of below it. This will cause it to only add one value to the list before returning, producing the list you see.
Unindent that line and it should work properly.
In Python, indentation is of primary importance. The code you have posted is incorrectly indented.
>>> def fibs(number):
... result = [0, 1]
... for i in range(number-2):
... result.append(result[-2] + result[-1])
... return result
...
>>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With