How to print Fibonacci sequence

Question:

I am working on a Python tutorial. I am getting an incorrect result as I try to work through an example.

This question does not answer my question.

I have defined my function like so:

def fibonaccci(sequence_length):
    "Return the Fibonacci sequene of length * sequence_length"
    sequence = [0,1]
    if sequence_length < 1:
        print("Fibonacci squence only defined fo length 1 or greater")
        return
    if 0 < sequence_length < 3:
        return sequence[:sequence_length]
    for i in range(2, sequence_length):
        sequence_length.append(sequence[i-1]+sequence[i-2])
    return sequence

Expected:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Actual:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/tmp/ipykernel_35261/4107038898.py in <module>
----> 1 fibonaccci(int(12))

/tmp/ipykernel_35261/2532562687.py in fibonaccci(sequence_length)
      8         return sequence[:sequence_length]
      9     for i in range(2, sequence_length):
---> 10         sequence_length.append(sequence[i-1]+sequence[i-2])
     11     return sequence

AttributeError: 'int' object has no attribute 'append'
Asked By: Evan Gertis

||

Answers:

You’re trying to append to the int parameter sequence_length instead of the length sequence. Just append to that instead:

def fibonaccci(sequence_length):
    "Return the Fibonacci sequene of length sequence_length"
    sequence = [0, 1]
    if sequence_length < 1:
        print("Fibonacci squence only defined for length 1 or greater")
        return
    if 0 < sequence_length < 3:
        return sequence[:sequence_length]
    for i in range(2, sequence_length):
        sequence.append(sequence[i - 1] + sequence[i - 2])
    return sequence
Answered By: pigrammer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.