Code challenge function returns None

Hi All,

I’m stuck at the 2nd challenge called Append Sum here:

Printing the append_sum function based on the code below should result in “[1, 1, 2, 3, 5, 8]”, but all I’m getting is “None” instead. As long as I reference ‘lst’ from within the function it has the right type and value but when the function returns it it just loses both. Why?

You forgot to use return on line 12. So difficult to explain this.

you call the function (on line 12), which when base case (line 6 till 8) is reached, returns a list, but the call now doesn’t return the list to the other recursive calls that still have to be resolved


Thank you so much! I’m going out on a limb a little bit with this attempt to create a loop (haven’t gotten to that section yet in the course).

As you suggested, I added in the else: section a “return lst” and now it’s working and still not working.

The line “print(append_sum([1, 1, 2]))” yields the right result now: [1, 1, 2, 3, 5, 8]. But when I click on “check result” on the challenges page, it says " append_sum([1, 1, 2]) should have returned [1, 1, 2, 3, 5, 8] , and it returned [1, 1, 2]" - so somehow it doesn’t detect the output as valid. That’s odd.

On another note, I see that the additional return statement solved my problem but I don’t understand why it works. The way I see it in the first 3 iterations the program jumps from line 6 to line 9, appends the list, adds to the counter and then line 12 makes it go back to line five. So nothing after line 12 should execute yet it still does because the additional “return” on line 13 solved the problem. If it’s not too much to ask, I would be grateful for any explanations. :slight_smile:

that was not what I suggested, line 12 is:


which should be:

return append_sum(lst)

I can also recommend this topic:

Recursive function calls

which explains something on recursion.

this is your base case:

if timesRun == 3:
   return lst

when we are doing recursion, the calls are stacked, until the base case is reached and then the calls are resolved (in reverse order)

so the base case return the list, which will resolve the last call in the stack. However, this call does not return anything, so the next function call to be resolved didn’t any return value. Which means we get None (the absence of a return value)

Thank you for the explanation. Guess I had quite a naive view of how complicated this is.

This is quite a reality check/confrontation. Took me a while as well before I could “visualize” this flow, walking through it step by step.

you could visualize the execution here:

Python Tutor - Visualize Python, Java, JavaScript, C, C++, Ruby code execution

maybe that will help some?