473,387 Members | 1,440 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

returning None instead of value: how to fix?

sam
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)
__________________________________________________ ____________________

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

Sep 22 '06 #1
8 2186
On 2006-09-22, sam <py********@googlemail.comwrote:
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)
Your immediate bug is that you're missing a return statement:

return recursive_halve(value)

But your recursive routine is overcomplicated with too many base
cases, and you haven't written it functionally. There's no need
to modify value directly in a functional procedure.

Here's another version.

def recursive_halve(value):
if value < 1.0:
return value
else:
return recursive_halve(value / 2.0)

Now imagine the call-stack when called with value 45.0 (using the
substitution model):

recursive_halve(45.0) -->
return recursive_halve(22.5) -->
return recursive_halve(11.25) -->
return recursive_halve(5.625) -->
return recursive_halve(2.8125) -->
return recursive_halve(1.40625) -->
return recursive_halve(0.703125) -->
return 0.703125

--
Neil Cerutti
Life is indeed precious, and I believe the death penalty helps
affirm this fact. --Edward Koch
Sep 22 '06 #2
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
Sep 22 '06 #3

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

Sep 22 '06 #4
sam
Missing a return on the last line is likely your immediate problem.

thanks to everyone for pointing this out. obviously, i had not
understood what was actually involved in a recursive call. i have
corrected it as suggested and it works fine now.
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.
yes, i could see this was nasty. i figured i'd go back and try and
streamline it afterwards. i wrote an insertion sort yesterday and i had
to cheat by putting two items into a new list to begin with, and only
then enter the nested loops to do the rest of it. i seem to be fighting
my way into a process to get a foothold, and only then trying to finish
it smoothly/elegantly. hopefully this will ease up with time and
practice.
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).
if i understand this correctly, you mean that the function will
terminate if it returns 'value' at the beginning, so the else: is
implicit in the fact that the interpreter has even got that far. i take
your point about trying to abbreviate what is, in effect, verbiage.

thanks again for all the answers. it boggles the mind that one can have
access to this almost immediate help at no charge.

sam

Sep 22 '06 #5
On 2006-09-22, sam <py********@googlemail.comwrote:
>Missing a return on the last line is likely your immediate
problem.

thanks to everyone for pointing this out. obviously, i had not
understood what was actually involved in a recursive call. i
have corrected it as suggested and it works fine now.

thanks again for all the answers. it boggles the mind that one
can have access to this almost immediate help at no charge.
But there is a charge. You're charged with asking your question
well, and you're charged with making some obvious effort to solve
the problem on your own. Those who take the trouble, as you did,
usually get excellent free help.

It's not out of the kindness of our hearts that we help. Heck, I
don't know what it is. Probably I just like reading my own drivel
on the internet and occassionally helping others is a good
excuse.

--
Neil Cerutti
Sep 23 '06 #6
sam a écrit :
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:
And forgot to return the result from the recursive call, I guess ?-)
Sep 23 '06 #7
Neil Cerutti a écrit :
(snip)
It's not out of the kindness of our hearts that we help. Heck, I
don't know what it is. Probably I just like reading my own drivel
on the internet and occassionally helping others is a good
excuse.
Lol !-)

+1 OTQOTW

Sep 23 '06 #8
Neil Cerutti wrote:
It's not out of the kindness of our hearts that we help. Heck, I
don't know what it is. Probably I just like reading my own drivel
on the internet and occassionally helping others is a good
excuse.
Weird, isn't it ? Good to know that it's not just me that thinks this
way.

Best,
George

Sep 24 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: Steven Bethard | last post by:
I have lists containing values that are all either True, False or None, e.g.: etc. For a given list: * If all values are None, the function should return None.
4
by: beliavsky | last post by:
If a function that normally returns N values raises an exception, what should it return? N values of None seems reasonable to me, so I would write code such as def foo(x): try: # code setting...
10
by: Sachin Garg | last post by:
Hi, When trying to return objects of type std::list<MyClass> from my function, I get a corrupt heap. (I checked using MSVC++ 7.0 runtime heap check facility) Basically, I am creating a...
11
by: JKop | last post by:
AnyClass Blah() { AnyClass poo; return poo; } As we all know, in the above, the compiler is entitled to:
25
by: Victor Bazarov | last post by:
In the project I'm maintaining I've seen two distinct techniques used for returning an object from a function. One is AType function(AType const& arg) { AType retval(arg); // or default...
13
by: Kirk McDonald | last post by:
Say I have a database containing chunks of Python code. I already have a way to easily load, edit, and save them. What is slightly baffling to me is how I can effectively pass this code some...
10
by: randomtalk | last post by:
hello, i have another problem i feel that i have to be missing something.. Basically, i've written a recursive function to find all the prime up to a number (lim).. here is the function: The...
13
by: agent-s | last post by:
I have a function, generally described as so: def function(args): if condition: if condition2: function(args+1) elif condition3: print "text" return True else:
70
by: junky_fellow | last post by:
Guys, If main() calls some function func() and that function returns the error (errno), then does it make sense to return that value (errno) from main. (in case main can't proceed further) ? ...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.