1

I am a beginner to programming and in this case cannot understand why this Python code doesn't work as expected.

I am trying to use recursion by calling a function within a function; calling the function n times, and reducing n by 1 to 0 with each loop at which point it will stop.

Instead my code prints 'freak' once, then I get a 'maximum recursion depth' error message.

def print_m():
    print ('freak')

def do_n(arg, n)):
    if n >= 0:
        print (do_n(arg,n))
        n = n - 1
1
  • 3
    You need to decrement n BEFORE your recursive call. Commented Aug 31, 2016 at 14:38

3 Answers 3

7

Recursion is not a loop!

You should be passing n - 1 to the recursive call instead of merely n, not subtracting one from n after this call.

Sign up to request clarification or add additional context in comments.

2 Comments

This solved it, thank you, though I the output is 'None' for all calls other than the initial one, which I don't understand. I'll go back to the text book and play around a bit more!
@Katy, it should be None as you're calling the function do_n recursively and printing the returned value. This function doesn't return anything, so you're getting a None.
1

Passing n-1 as parameter to recursive call fixes the problem.

Comments

0

In the recursive call in line 6 you should pass print (do_n(arg,n-1)) .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.