The following is a recursive function designed to return the factorial of a number.

def factorial(number, target):
	if number == 1: 
		return target
	else:	
		target = target*number
		factorial((number-1), target)

print factorial(7, 1)

As you'll see if you run it however it doesn't return my 'target' variable (the factorial of 'number') but instead returns 'None'. I can get it to produce the factorial by changing line 3 from 'return target' to 'print target', but this is an imperfect solution because it doesn't allow me to use the output of this function in subsequent code. So, how do I get the function to 'return' the target?

While I'm at it, I'd also appreciate some help on this next bit of code which is designed to count down from 12 to 3.

def reduce(n):
	while n != 3:
		print n
		reduce((n-1))
			
reduce(12)

When I run it, it gets down to the number 4 and then ends up in an infinite loop, endlessly repeating '4'. Can anyone explain why?

Thanks,
Paul.

You don't return or receive anything for numbers not equal to zero. The function calls itself many times. Each function call must receive the return value when the function it calls finishes, and then return that value to the function it was called by.

def recursion_test(value):
    """ recursion example incrementing a counter for each function, and
        printing each function value for that function call
    """
    print "value now =", value
    if value > 10:              ## exit recursion loop
        return value
    new_value = recursion_test(value+1)
    return new_value

print recursion_test(0)

For recursion, (1) there should be a terminating condition.
(2) each successive call to the recursive function is solving a smaller subset of the problem.

def reduce(n):
    print n
    if n==3:        # condition 1
       return
    reduce((n-1))   # condition 2
reduce(12)

Hi

def factorial(number):
	if number == 1: 
                #1! = 1
		return number 
	else:	
                #n! = n * (n-1)!
		return number * factorial(number-1)
 
# print 7!
print factorial(7)

Okay, thanks for the responses. I think I'm beginning to get it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.