473,657 Members | 2,530 Online
Bytes | Software Development & Data Engineering Community
+ 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 3147
"Derek Rhodes" <rh****@worldpa th.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('unsu pported 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******** *************** *************** @python.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('unsu pported 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
1978
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
2881
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 a sequence of spaces; recursive function 2 uses input to display ascending sequence of digits; likewise, recursive function 3 uses input to display descending sequence of digits. I have not followed the instructions completely regarding the...
4
9047
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. However, it is not as straightforward to determine the base address for my stack space. The approach I have taken is to save the address of an automatic variable in main( ), and assume this is a fairly good indicator of my base address. Then, I can...
5
2800
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 needed during cleanup. (Finally the two forms are obviously not equivalent in a recursive call to `main'). My questions are
6
2262
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, (xmlChar*)key.c_str() ) ) { cout << root_node->name << ": " << xmlNodeListGetString(doc,
3
2950
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 id. I have the following but it doesn't work well (algorighm issue) : var cn = null; function getChildElement(parent, childID){ for (var i=0; i<parent.childNodes.length; i++){ cn = parent.childNodes;
14
3473
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 of parent/child relationship. Now I would like to get all children of a given "Device" object and thought that it would be the best way to use recursive function.
1
1425
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 (1 value nite, 6 premium nites, they should get the value nite free)
2
2284
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 ----nextSibling ---->0 | |
0
8413
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
8324
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
8740
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
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
5642
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
4173
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
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.