2017-09-25 82 views
-1

我正在研究一個hang子手程序(這是一個家庭作業),這是它告訴玩家他們迄今爲止猜到的部分。這裏是我的編程:Python應該返回str返回'None'

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'] 

當我問它打印出來theWord我期待它發出下劃線和字母_ pp_ e的組合,相反,它給了我None。我無法弄清楚我的問題是我在第2行放置theWord的位置,還是與第二行的位置相關,或者與其他地方完全不同。

+3

你什麼時候期待'else'執行? 'char'有什麼值'char not in lettersGuessed'是假的_and_'char in lettersGuessed'是False? – Kevin

+0

這是你的代碼嗎?它有空白錯誤。 – doctorlove

+1

你的return語句放錯了位置,它應該在for循環之後。 –

回答

5

你必須整個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'])) 
0

就抹掉這個else和修復縮進。像這樣:

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 returns nothing nothing。這是因爲你的回報永遠不會被調用。你只是不要進入這個其他的。你寫了一個if語句,並且elif不在,這意味着你在這兩個語句中覆蓋了所有的情況,然後沒有意義寫一個else。