2

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?

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

1

I just indented the code and it worked correctly for me:

def fibs(number):
    result = [0, 1]
    for i in range(number-2):
        result.append(result[-2] + result[-1])
    return result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.