List loop fail

Trying to be clever with question #2 of " Python Code Challenges: Lists", see link below …

I was able to solve the problem by manually repeating the code three times. But I wanted to do the bonus part that challenges me to use a loop. So frustrating that I cannot. This is what I came up with but it didn’t work because I was stuck in an infinite (?) spinning loop thing …

index = 0
while index <= 3:
def append_sum(lst):
lst.append(lst[-1] + lst[-2])
return lst
index += 1

Someone please explain what is wrong here and what the correct loop code is. Thank you.

Also, can someone teach me what to do so that my indents show up when I post here?

There would be some difficulty defining a function in a while loop, for starters. Ping back so we may continue this discussion.

I am going to go back and review the lesson on Python 3: Loops now …

This was my next try. See my new code attempt below. Still wrong, but at least not stuck in an infinite loop …

def append_sum(lst):
–>tracker = 0
–>while tracker <= 3:
----->lst.append(lst[-1] + lst[-2])
----->tracker += 1
----->return lst

Unfortunately this is not correct because my good code lst.append(lst[-1] + lst[-2]) only runs once. Why? With my while loop tracker, I’ve written the code so that it should run three times!

return inside the loop?

1 Like

YAYYYYY!! Also, I changed my while loop tracker to <=2 so that the code runs three times (tracker = 0, tracker = 1, and tracker = 2) instead of four times.


For my own notes, I notice that I still need a lot of practice on loops and on global/local placement.

Thank you mtf!

1 Like