returning None instead of value: how to fix?

Carl Banks pavlovevidence at gmail.com
Fri Sep 22 16:27:15 EDT 2006


sam wrote:
> def recursive_halve(value):
>
>     if value < 1:
> 	print value
> 	return value
>     else:
>     	value = value/2
>     	print value
>     	if value < 1:
> 	    return value
>     	else:
> 	    recursive_halve(value)

Missing a return on the last line is likely your immediate problem.

You have more subtle problems, though.  First, you have needlessly
reduplicated value<1 test--the first thing recursive_halve does is to
check whether value<1, so there's no need to check whether value<1
before calling it.

Second, you have redundant branching logic.  Look at your first else
statement.  It does nothing; the else doesn't affect whether the stuff
inside it gets executed or not; it's redundant.  It's better style to
not to have such redundancy (either by omitting the else, or having a
single return point).

The following should do exactly what you want.

def recursive_halve(value):
    if value < 1:
        print value
        return value
    value = value/2
    print value
    return recursive_halve(value)


Carl Banks




More information about the Python-list mailing list