Katy
Katy

Reputation: 19

Recursion code not working as expected - Python 3

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

Upvotes: 1

Views: 80

Answers (3)

user3500741
user3500741

Reputation: 61

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

Upvotes: 0

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22061

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

Upvotes: 1

ForceBru
ForceBru

Reputation: 44906

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.

Upvotes: 7

Related Questions