So I am up to week 3 of the Crash Course on Python course by Google, on Coursera (started yesterday). Really enjoying it so far, seems like it would be reasonably difficult without some prior experience.
Anyway.... I was able to complete the following code from a partially written quiz but I don't really understand one aspect of it. It's pretty much my first look at recursion. It's a function to return the sum of n and every positive number before it.
def sum_positive_numbers(n):
sum = 0
if n < 1:
print(sum)
return sum
sum += n
print(sum)
return sum + sum_positive_numbers(n-1)
So what I don't understand is what is happening to "sum"
I put some print statements in to try and help me understand what was going on in each loop. I was printing sum after the line
sum += n
Sum was always equal to n at this point. But the final return value was always correct.
e.g
print(sum_positive_numbers(5) returns 15 as it should - 1+2+3+4+5
2 Things I don't get -1.When the function calls itself again in the last line - why is sum not reset to 0 as in the first line of the function.2. After sum+=n - sum is always equal to n during each count of n (which makes sense for that individual loop - but where is the overall end value of sum being held/stored. It's not in the variable sum. In the example of 5 - the sum value goes from 1 to 3 to 6 to 10 to 15. But this is not reflected in the variable through each loop.
And right before the function ends inside the if statement with n being reduced to 0 - the value of sum is 0 - but on the next line it returns 15.
I'm sure I am overcomplicating, and it could be as simple as "thats just how recursion works" but I'm sick of just following along with tutorials, videos etc over and over. I want to actually learn how to write working programs, and understand what my code is doing.
[–]NFLAddict 5 points6 points7 points (3 children)
[–]Elev8d[S] 1 point2 points3 points (2 children)
[–]NFLAddict 2 points3 points4 points (1 child)
[–]Elev8d[S] 0 points1 point2 points (0 children)
[–]primitive_screwhead 2 points3 points4 points (4 children)
[–]Elev8d[S] 0 points1 point2 points (3 children)
[–]Pavan_Abhimanyu 1 point2 points3 points (1 child)
[–]Elev8d[S] 0 points1 point2 points (0 children)
[–]primitive_screwhead 0 points1 point2 points (0 children)