简体   繁体   English

应该返回str的Python返回'None'

[英]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 . 当我要求它打印出theWord我希望它发送下划线和字母_ pp_ e的组合,但是却给了我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. 我无法弄清楚我的问题是否是我在第2行中放置了theWord ,或者它是否与else有关,或者它是否完全不同。

You have to return something after successful execution of the entire for-loop: 成功执行整个for循环后,您必须return一些内容:

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. 您编写了一个if in语句,而一个elif not in语句,这意味着您覆盖了这两个语句中的所有情况,然后就没有意义再编写else了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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