Home > Software design >  I've written a simple program to automate the Fibonacci sequence and it's not working and
I've written a simple program to automate the Fibonacci sequence and it's not working and

Time:09-21

I'm trying to get a better understanding of functions in python and decided to try automating the Fibonacci sequence. This is my code so far and it's not doing what it's supposed to. I can't figure out why it's not working. Can someone please point my errors out?

I'm using the stop variable as a definite stop and the length variable telling the program how far I'd like it to execute the code. Below is my code:

length = 6
stop = 10

def append_sum(lst):
    while length <= stop:
        return lst.append(lst[-1]   lst[-2])

print(append_sum([1, 1, 2]))

CodePudding user response:

For something like this, I would just Google it.

a = int(input('Give amount: '))

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a   b

print(list(fib(a)))

Result:

Give amount: 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

CodePudding user response:

The length variable in your code doesn't change, so the stop doesn't work because of that. Also even if it did, you return the list after it enters the while function, so at most it will do one iteration. lst.append() will mutate the list, but won't return a copy of it so , you can't return lst.append()

  • Related