简体   繁体   中英

Python supposed to return str returns 'None'

I am working on a hangman program (it is a homework assignment) and this is the part where it tell the player what they have guessed so far. Here is my programming:

def getGuessedWord(secretWord, lettersGuessed):
theWord=''
for char in secretWord:
    if char not in lettersGuessed:
        char='_ '
        theWord+=char
    elif char in lettersGuessed:
        theWord+=char
    else:
        return theWord
print (getGuessedWord('apple', ['e', 't', 'i', 'p', 'r']

When I ask it to print out theWord I am expecting it to send out a combination of underscores and letters _ pp_ e , but instead is gives me None . I cannot figure out if my problem is where I placed theWord in line 2, or if it has to do with the else, or if it somewhere completely different.

You have to return something after successful execution of the entire for-loop:

def getGuessedWord(secretWord, lettersGuessed):
   theWord=''
   for char in secretWord:
      if char not in lettersGuessed:
         char='_ '
         theWord+=char
      elif char in lettersGuessed:
         theWord+=char
   return theWord #here, returning theWord
print (getGuessedWord('apple', ['e', 't', 'i', 'p', 'r']))

Just erase this else and fix the indentation. Like this:

def getGuessedWord(secretWord, lettersGuessed): 
    theWord=''
    for char in secretWord:
        if char not in lettersGuessed:
            char='_ '
            theWord+=char
        elif char in lettersGuessed:
            theWord+=char
    return theWord

print (getGuessedWord('apple', ['e', 't', 'i', 'p', 'r']

Actualy your function is returning nothing. It's because your return is never called. You just don't enter in this else. You wrote a if in statement and an elif not in, it means you covered all cases in these two statements, then have no sense write an else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM