+ 1
Please help why are x and y being added together ? What am I missing
def rec(x,y): if x == 0: return y: if y != 0: return rec( x-1, y+1) print(rec(3,4)) # Output is 7 # why is it not (2,5)
11 Respostas
+ 7
It is a recursive function (it calls itself).
It has two arguments. If the first argument x is zero, the result is the other argument.
Otherwise x is decreased and y is increased, and the function is called with these new numbers again.
What happens effectively:
rec(3, 4) =
rec(2, 5) =
rec(1, 6) =
rec(0, 7) =
7 is returned through the call stack
+ 5
Recursion is a tricky topic, I see you are doing the Python Beginner course and this is covered in the intermediate course.
Return is giving back a value to the place where the function was called. But in this case, the last line of the function returns a new invocation of the same function, which is yet to be calculated with the new values. This could go on forever, but in recursion we always have a "base case" which is supposed to stop this endless loop. In this one, the recursion is stopped when either X or Y reach 0.
+ 2
O ok thanks I thought it was adding the two numbers 2 and 5. Also I thought you needed while or for to loop. Does the return start the sequence again. Your help is much appreciated I am very new to all this.
+ 2
Thank you for your help. I understand it now. Its quite simple once I read it again. 👍
+ 2
Because you return the def rec ,it will start the code again and again. It will go on forever until x or y is == 0.the function calls itself.. maybe someone more advanced could explain it better.
+ 1
I can't understand that can you explain it !!!!
+ 1
Each time X will -1 and y will + 1. It will stop once either == 0
0
def rec(x,y):
if x == 0:
return y # remove ":" (The colon)
if y != 0:
return ( x-1, y+1) # remove "rec"
print(rec(3,4))
0
Sorry the : after return was a misprint. It still adds X and y together. I am just not sure why
0
Why does putting the rec after the return add X and y
0
Ello