Recrusion exercise

hey again
i ve learned about recrusion in python today and i ve been doing some exercises about it
and ive come across this one but sadly it had no solution with it in the pdf
this is what the exercise says
‘Write a function using recursion to print numbers from 0 to n’
and this is my answer

def print_numbers(n,k=0):
    if n==k:
        print(n)
    else:
        print(k)
        return print_numbers(n,k+1)



print_numbers(5)

the code run with no problems but my question is ‘is this the most efficient and acceptable way’
thank you

Here’s another approach. Not necessarily more efficient or more acceptable.

def print_numbers(n):
    if n > 0:
      print_numbers(n - 1)
    print(n)

print_numbers(5)

The return here is unnecessary, but causes no harm:

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.