How to do an accountant recursively?

0

I need to do a recursive function that counts from 1 to a number entered by the user.

I have this:

def contador(num):
    #caso base
    if num == 1:
        return num
    else:
        return contador(num)

num=int(input("Hasta que número quieres llegar ?"))

print (contador(num))
    
asked by Álvaro 19.01.2018 в 22:28
source

3 answers

1

I like to complicate a bit the logic, I hope it helps you.

def contador(num, lista=[], cont=0):
  cont+=1
  lista.append(cont)
  if cont < num:
    return  contador(num, lista, cont) 
  else:
    return lista
num=int(input("Hasta que número quieres llegar ?"))
print(contador(numm))
    
answered by 20.01.2018 в 00:06
1

In your code the only thing that was really needed was to decrease the counter in the recursive call counter (num-1), and print at the beginning of the function.

def contador(num):
     print(num)
     if num == 1:
        return
     else:
        return contador(num-1)

num=int(input("Hasta que numero quieres llegar ?"))    
contador(num)
    
answered by 19.01.2018 в 22:49
0

According to your code you can perform a recursive function to print the number of items you request in this way:

def contador(num, count=0):
    #caso base
    print count
    if num == 0:
        return "Termina conteo en: %s" % count
    return contador(num-1, count+1)

num=int(input("Hasta que numero quieres llegar?"))

print (contador(num))

I add a online demo .

    
answered by 19.01.2018 в 23:08