0
It’s my first question here, so I’ll be brief: I’m having trouble with the code below:
def nat(n):
if n == 50:
return 0
else:
return nat(n+1)
print(nat(1))
Turns out it’s a recursive question in Python, I must print the first 50 natural numbers, but my output always returns '0':
0
I don’t understand almost anything about it, I have already solved the issue in C and Python, but using repetition structures, but in this way that was presented to me, I am not managing to solve the same problem. Does anyone have an orientation as to where the error(s) is? Reminder, I don’t need problem solving, just a guide to where I’m missing, if possible.
There are two returns on the function
n
: one returns a recursive call, without changing its result at all; the other returns 0, simply. Thus, you can return 0 or return the computation of something without applying any change, and that computation always returns 0. (I am ignoring entries greater than 50, which would be infinite and would never return)– Jefferson Quesado
It was not very clear to me, so I could give an example, friend? (As I mentioned above, I’m a bit of a layman, rs)
– Leidenschaft
According to its function, I will take from 48 and check the resulting value,
nat(48) ==> nat(48+1) ==> nat(48+1+1) ==> 0
– Jefferson Quesado
Ahh, thanks a friend
– Leidenschaft