[Tutor] Recursion always returns None

Steve Willoughby steve at alchemy.com
Tue Aug 28 13:52:55 CEST 2012


On 28-Aug-12 04:23, Dharmit Shah wrote:
> 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 :

I'm struggling to understand why you're using recursion here.
It serves no evident purpose for what you're doing, and given a large 
dictionary of words, could seriously tank the performance of the 
application, quite possibly run it out of resources and crash it altogether.

But since you're using recursion, note that when you make your recursive 
call, you're ignoring the return value from that call, so no returned 
value ever gets propagated out to the outer layers of recursion.

If the outermost layer took the recursion (length of the chosen word is 
wrong), it calls itself and then never takes the branch including the 
return statement at all.  ("return word" is never executed in that 
case). This causes the function to just 'fall off' the end which 
implicitly returns None.


HTH

>
> [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
>


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list