473,594 Members | 2,694 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 3146
"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
1975
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
2879
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
9041
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
2796
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
2261
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
2947
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
3469
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
1423
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
2279
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
7954
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
7882
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
8259
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8377
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
8016
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,...
1
5836
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3905
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2391
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
1
1487
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.