returning None instead of value: how to fix?
georgeryoung at gmail.com
georgeryoung at gmail.com
Fri Sep 22 15:53:51 EDT 2006
sam wrote:
> i am starting to experiment with recursion, and decided to write a
> fairly trivial little program which took a float as input, then called
> a function to halve it recursively until it was less than 1:
>____________________________________________________________________
> import recursive_halve_module
>
> raw_value = raw_input('please enter the number you would like to halve: ')
> value = float(raw_value)
> final_value = recursive_halve_module.recursive_halve(value)
> print final_value
> raw_input('hit enter to close:')
> 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)
^^^^^^^
This needs to be:
return recursive_halve(value)
You were executing the function, but not returning the result.
-- George
> it works fine apart from printing 'None' instead of 'final_value' at
> the end. however, if you enter a value that is already less than 1, it
> prints 'final_value' (i.e. that very same number) just fine.
>
> now, it looks to me like only 'value' can be returned: either right at
> the beginning (for values less than 1) or when you eventually get down
> to below 1 after x function calls. but clearly that's not the case. i
> understand that 'None' is returned by default by functions in Python.
> my question is: how am i slipping into that default despite seemingly
> (to me at least) avoiding it through explicitly returning something
> else?
>
> thanks in advance,
>
> sam
More information about the Python-list
mailing list