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

def factorial(number, target):
	if number == 1: 
		return target
		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

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?


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)

Edited 6 Years Ago by woooee: n/a

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
    reduce((n-1))   # condition 2


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

Edited 6 Years Ago by zaghaghi: n/a

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

This question has already been answered. Start a new discussion instead.