Recursion Problem in Python

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))

It happens that it's a recursive question in Python, I should print the first 50 natural numbers, but my output always returns '0':

0

I do not understand almost anything about the subject, I have already solved the question in C and Python, but using repetition structures, but in this way I was presented, I can not solve the same problem. Does anyone have an orientation of where is the error (s)? Reminder, I do not need problem solving, just a guide where I'm wrong, if at all possible.

    
asked by anonymous 28.11.2018 / 04:58

1 answer

2

In your code you are doing the following:

#define a  função nat
def nat(n):
    if n == 50:
        return 0
    else:
        return nat(n+1)

#chama a função para printar o valor retornado
print(nat(1))

So far so good, the return is in accordance with what you described.

You call the function with value n=1 , as the value of n is not equal to 50 will return the value of nat(n=2) , and so on until finally n=50 and returns 0 , which is the value printed.

So, in your code: nat(1) = nat(2) = nat(3) = ... = nat(50) = 0

I think it's a little indentation problem with a few minor adjustments.

I think it would be this, or something close, what you want to do:

#Define a função
def nat(n):
    if n == 50:
        return
    else:
        #printa e faz a chamada recursiva
        print(n)
        nat(n+1)

#chama a função
nat(1)
    
28.11.2018 / 05:19