[Tutor] Recursion always returns None
Dharmit Shah
shahdharmit at gmail.com
Tue Aug 28 13:23:27 CEST 2012
Hello,
I am trying to do the following :
1) Ask user for the length of the word that he'd like to guess (for
hangman game).
2) Pick a random word from /usr/share/dict/words (which I understand
is not the best choice for hangman).
3) Call a function that would pick a random word to proceed further.
Below is the code for the part I described above :
[code]
#!/bin/env python
import random
def pick_random(l, ln): # picks a random word from the list
l of length ln
global mystery
word = random.choice(l)
if word.__len__() != ln:
pick_random(l, ln) # recursion
else:
print "Should return %s" % word # prints the chosen random
word correctly
return word # always
return None, why? :(
if __name__ == "__main__":
ln = raw_input("How long word can you guess (number of alphabets) : ")
ln = int(ln)
l = []
with open("/usr/share/dict/words", "r") as f:
for i in f.readlines():
i = i.split("\n")[0]
if i.isalpha():
l.append(i)
word = pick_random(l, ln)
print word
[/code]
Sample output :
$ python hangman.py
How long word can you guess (number of alphabets) : 6
Should return inarch
None
$
The problem is that the last line "print word" always prints None. I
know I am doing something wrong in the recursion part of the function
"pick_random". Can someone please point what I am missing. Thank you!
Cheers,
Dharmit
--
Dharmit Shah
www.about.me/dharmit
More information about the Tutor
mailing list