473,799 Members | 3,214 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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('plea se enter the number you would like to halve:
')
value = float(raw_value )

final_value = recursive_halve _module.recursi ve_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 2209
On 2006-09-22, sam <py********@goo glemail.comwrot e:
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('plea se enter the number you would like to halve:
')
value = float(raw_value )

final_value = recursive_halve _module.recursi ve_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('plea se enter the number you would like to halve: ')
value = float(raw_value )
final_value = recursive_halve _module.recursi ve_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********@goo glemail.comwrot e:
>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
3404
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
1605
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 y and z return y,z except: return None,None
10
2912
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 local object
11
1946
by: JKop | last post by:
AnyClass Blah() { AnyClass poo; return poo; } As we all know, in the above, the compiler is entitled to:
25
2947
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 construction and then.. // some other processing and/or changing 'retval' return retval; }
13
1704
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 arguments, run it, and somehow get a return value. (Acutally, in the process of writing this post, I figured out a pretty good way of doing it. Here's the rest of my post and the solution I came up with. Enjoy my thought process!) Right now I'm...
10
2442
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 function basically takes in a list of all the prime number found, it takes the next number to be tested for (next) and the limit it will go up to. It divide next by the list of previous prime numbers if next is not bigger than lim, count up all the...
13
2261
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
3640
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) ? eg. int main(void) {
0
9688
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9546
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9078
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5590
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.