# Having Trouble Understanding Pything Recursives.

I know it's basically a function calling itself, but no matter how I try, it always drops a lot of errors.

I don't really understand recursives, so let me analyze it and correct me if I'm wrong.

def recursive(n):
n += n
if n == 1:
return n
else:
return n + recursive(n-1)

"def recursive(n):" - Creates a functions that requires a "n" parameter.
"n += n" - Multiplies given number by 2 or adds the given number to itself.
"if n == 1" - Checks if the given "n" parameter is equals to 1.
"return n" - If the If statement is true, it returns "n" parameter.
"else:" - If the if statement is false, execute whatever is after.
"return n + recursive(n-1)" - The part I don't really understand.

+1 vote
answered Nov 19, 2023 by (89,130 points)

The last line: return the current value of n plus anything that would be the result of the same calculation for n-1.

But... this function does not work. As soon as you enter the function, it doubles the value of n (as you correctly said before). The recursion terminates when (you do not call the recursive function anymore) n reaches 1. What number doubled equals 1? 0.5

But the code you shared is called with n=12 and it will keep growing, and will never reach 0.5, so this is an infinite recursion and the runtime will terminate the program.

By the way, the code you shared in the question is different from the code you linked. The one you linked is also an infinite recursion, but for that, you'll need an integral that is no larger than 1 (so it could be 1, 0, -1, -2, etc) and then the recursion will naturally terminate and a result is produced.

commented Nov 20, 2023 by (5,350 points)
Yeah I know the code is different than the one I linked in, while asking the question I realised that maybe the problem is the function doesn't know what to do, since I didn't give it anything to do other than checking if some statements are true. I tried it with a line that would actually do something with the given number, and return it if some statements are true. Once I realised it doesn't work, my ass was too lazy to correct it. Thank you for your time :) It helped, and finally after 2 years of working with python, I understand recursion yaay :D
commented Nov 20, 2023 by (89,130 points)
I'm glad I could be of service.

Keep on coding! :)