473,466 Members | 1,639 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Recursive function not returning value

using
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32

OK, I have a recursive function that should return a list, but doesn't

<start session>

def test(word):
if type(word) == str:
print "it's a word"
test([word])

if type(word) == list:
print "The conditional worked, see ->", word
return word
a = test('foobity') it's a word
The conditional worked, see -> ['foobity'] print a

None

</end session>

What am I missing?

-derek.
Jul 18 '05 #1
4 3137
"Derek Rhodes" <rh****@worldpath.net> writes:
if type(word) == str:
print "it's a word"
test([word])


The last line tests [word] and throws away the value. YOu have to say
"return test([word])".
Jul 18 '05 #2
Derek Rhodes <rhoder <at> worldpath.net> writes:
OK, I have a recursive function that should return a list, but doesn't

def test(word):
if type(word) == str:
print "it's a word"
test([word])

if type(word) == list:
print "The conditional worked, see ->", word
return word


By default, if a Python function does not hit a return statement before the
end of the function, it returns the None value. Notice that if word is a str,
your function executes the first if-block, including the recursive call and
then skips the second if-block. So in this case, you never hit a return
statement and so Python returns None. You probably meant to write:

def test(word):
if type(word) == str:
return test([word])
if type(word) == list:
return word

If you run into these kind of mistakes frequenly, it might be worth having
only one return point in each function. You would then write your code
something like:

def test(word):
if isinstance(word, str):
result = test([word])
elif isinstance(word, list):
result = word
else:
raise TypeError('unsupported type %r' % type(word))
return result

Of course, this particular example probably doesn't merit a recursive function
anyway, but you get the idea...

Steve
Jul 18 '05 #3
Derek Rhodes wrote:
OK, I have a recursive function that should return a list, but doesn't

<start session>

def test(word):
if type(word) == str:
print "it's a word"
test([word])

if type(word) == list:
print "The conditional worked, see ->", word
return word

What am I missing?


You are forgetting to return the value.

change this part ::

if type(word) == str:
print "it's a word"
test([word])

to

if type(word) == str:
print "it's a word"
return test([word]) # return the result of test([word])
George
Jul 18 '05 #4

"Steven Bethard" <st************@gmail.com> wrote in message
news:ma**************************************@pyth on.org...
Derek Rhodes <rhoder <at> worldpath.net> writes:
OK, I have a recursive function that should return a list, but doesn't

def test(word):
if type(word) == str:
print "it's a word"
test([word])

if type(word) == list:
print "The conditional worked, see ->", word
return word


By default, if a Python function does not hit a return statement before
the
end of the function, it returns the None value. Notice that if word is a
str,
your function executes the first if-block, including the recursive call
and
then skips the second if-block. So in this case, you never hit a return
statement and so Python returns None. You probably meant to write:

def test(word):
if type(word) == str:
return test([word])
if type(word) == list:
return word

If you run into these kind of mistakes frequenly, it might be worth having
only one return point in each function. You would then write your code
something like:

def test(word):
if isinstance(word, str):
result = test([word])
elif isinstance(word, list):
result = word
else:
raise TypeError('unsupported type %r' % type(word))
return result

Of course, this particular example probably doesn't merit a recursive
function
anyway, but you get the idea...

Steve


WOW, thanks everyone for the quick reply!

-Derek.
Jul 18 '05 #5

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

Similar topics

2
by: actuary77 | last post by:
I am trying to write simple recursive function to build a list: def rec(n,alist=): _nl=alist print n,_nl if n == 0: print n,_nl return _nl else:
2
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays...
4
by: Victor | last post by:
Hello, I've got a situation in which the number of (valid) recursive calls I make will cause stack overflow. I can use getrlimit (and setrlimit) to test (and set) my current stack size. ...
5
by: Seong-Kook Shin | last post by:
Hi, I'm reading Steve's "C Programming FAQs" in book version, and have two question regarding to Q11.16 ... Also, a `return' from `main' cannot be expected to work if data local to main might be...
6
by: Uwe Grawert | last post by:
I have the following recursive function: string find_value_by_key (xmlDocPtr doc, xmlNodePtr root_node, const string& key) { while(root_node != NULL) { if(! xmlStrcmp( root_node->name,...
3
by: samuelberthelot | last post by:
Hi, I'm trying to write a recursive fucntion that takes as parameters a html div and an id. I have to recurse through all the children and sub-children of the div and find the one that matches the...
14
by: Fabian Steiner | last post by:
Hello! I have got a Python "Device" Object which has got a attribute (list) called children which my contain several other "Device" objects. I implemented it this way in order to achieve a kind...
1
by: J. Frank Parnell | last post by:
arrrrrg: Condo for rent has 3 price tiers (for different times of the year): value regular premium For every 7 nites they stay, they get 1 free, and that free one should be the cheapest night...
2
by: aaragon | last post by:
Hi guys, Is there a way to return a functor from a recursive call that takes different paths? Let's say that I have a tree structure like: root | first child ---- nextSibling ----nextSibling...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.