0

whats the difference between the following two codes:

this one gives me recursion error def collatz(n): if n == 1: print(1) if n%2 == 0: print(n/2) collatz(n/2) else: print(n*3 + 1) collatz(n*3 + 1) collatz(7) this one works properly: def collatz(n): if n == 1: return 1 if n%2 == 0: print(n/2) collatz(n/2) else: print(n*3 + 1) collatz(n*3 + 1) collatz(7) according to me in the 1st code when we arrive at 1, it should be just printed and code should be stopped...why is that not happening but it happens when we return 1????

18th May 2020, 8:53 AM
PRO
PRO - avatar
4 Respuestas
+ 2
print() doesnt stop your code, it just displays what you tell it to. when you return a value in a function, the function will not go any further.
18th May 2020, 8:57 AM
Slick
Slick - avatar
+ 4
you can see the benefit of using the return statement here. When you print, it directly outputs, but when you retrn, you can execute the function again bcz, that function (recurssive) becomes the part of thay return statement. So the output is not completed without that.
18th May 2020, 9:00 AM
M Tamim
M Tamim - avatar
+ 1
thank you Slick and M Tamim
18th May 2020, 9:33 AM
PRO
PRO - avatar
+ 1
The first code sample is an infinite loop, that will be only terminated when the program exeed the recursion level or when the memory consumption is too high.
18th May 2020, 10:08 AM
Lothar
Lothar - avatar