Home > OS >  Recursive function returns None when recurred
Recursive function returns None when recurred

Time:05-29

In my guessing game, when the correct (five-letter) word is entered on the first try, it works fine (which means, it returns the correctly guessed word).

But, when the correct word is entered on any other than the first try, it is returning None instead.

def word_list():
    with open("MyFile.txt", "r") as file:
        allText = file.read()
        return list(map(str, allText.split()))

def next_guess(word_list):       
    ges_word = input("Please enter a guess: ")    
    if ges_word in word_list:
        print(ges_word)
        return ges_word 
    else:    
        next_guess(word_list)

def play():    
    guessed_word = next_guess(word_list())
    print(guessed_word)

play()

Behavior when the correct letter is entered on the first try:

> Please enter a guess: kumar
> kumar
> kumar

Behavior when the correct word is entered on the second try:

> Please enter a guess: brake
> Please enter a guess: kumar
> kumar
> None

CodePudding user response:

The issue is that, when the player fails a guess, it goes to the recurring branch:

if ges_word in word_list:
    print(ges_word)
    return ges_word 
else:    
    next_guess(word_list)

When you do next_guess(word_list), you are indeed recurring the function, but when the result is returned by the recurring call, you are not returning that value from the top (very first) function call.

Try this:

else:    
    return next_guess(word_list)

In Python, if you don't exit a function on an explicit return statement, it implicitly returns None.

  • Related