2013-04-17 186 views
0

我有以下方法調用:爲什麼我的方法返回None?

NCOLS = 3   
NPEGS = 4 

first_guess = [] 

print("calling first guess method") 
first_guess = firstGuess(NCOLS, NPEGS, first_guess) 
print("after method call: " + str(first_guess)) 

firstGuess方法:

def firstGuess(NCOLS, NPEGS, first_guess): 
"""Used for setting up the first guess of the game""" 
    print("in firstGuess method") 
    for c in range(1, NCOLS + 1): 
    if len(first_guess) == NPEGS: 
     print("about to return first guess: " + str(first_guess)) 
     return first_guess 
    else: 
     first_guess.append(c) 

    print("out of for loop, first_guess len is " + str(len(first_guess)) + ", " + str(first_guess)) 
    if len(first_guess) <= NPEGS: #there were less color options than pegs 
    firstGuess(NCOLS, NPEGS, first_guess) 

這似乎是返回None一個原因,我想不通。

這裏是我的輸出:

calling first guess method 
in firstGuess method 
out of for loop, first_guess len is 3, [1, 2, 3] 
in firstGuess method 
about to return first guess: [1, 2, 3, 1] 
after method call: None 
Traceback (most recent call last): 
File "mastermind.py", line 323, in <module> 
sys.exit(main()) 
File "mastermind.py", line 318, in main 
playOnce() 
File "mastermind.py", line 160, in playOnce 
first_guess = first_guess + str(g[0][i]) 
TypeError: 'NoneType' object is not subscriptable 

爲什麼返回None,而不是[1, 2, 3, 1]

回答

3

的問題,你打回來就是你的遞歸調用不會返回其結果。

因此,它打印出「for for loop ...」,然後它進行遞歸調用。這個遞歸調用然後成功地返回了一些東西......但是外部調用忽略了這個並且結束了,這意味着你得到了None

呼叫之前,只需添加一個returnfirstGuess

print("out of for loop, first_guess len is " + str(len(first_guess)) + ", " + str(first_guess)) 
if len(first_guess) <= NPEGS: #there were less color options than pegs 
    return firstGuess(NCOLS, NPEGS, first_guess) 

這仍然留下,你不返回任何路徑(如果你能「出的for循環」,然後len(first_guess) > NPEGS)...但你沒有任何邏輯去做任何有用的事情。如果您認爲永遠不會發生,您可能需要添加某種assertraise

+0

啊,我看到謝謝!愚蠢的錯誤。 – Deekor

0

這是因爲你的代碼中有一些路徑不會以顯式返回任何東西結束。

你在哪裏調用firstGuess遞歸,你應該做return firstGuess(...)?儘管如此,你仍然會遇到一些情況,你不會返回任何東西。您應該在最後的if聲明之後添加最終的return first_guess聲明。

試試這個:

def firstGuess(NCOLS, NPEGS, first_guess): 
    """Used for setting up the first guess of the game""" 
    print("in firstGuess method") 
    for c in range(1, NCOLS + 1): 
    if len(first_guess) == NPEGS: 
     print("about to return first guess: " + str(first_guess)) 
     return first_guess 
    else: 
     first_guess.append(c) 

    print("out of for loop, first_guess len is " + str(len(first_guess)) + ", " + str(first_guess)) 
    if len(first_guess) <= NPEGS: #there were less color options than pegs 
    return firstGuess(NCOLS, NPEGS, first_guess) 
    return first_guess 
0

你的最後兩行更改爲

if len(first_guess) <= NPEGS: #there were less color options than pegs 
    return firstGuess(NCOLS, NPEGS, first_guess) 
else: 
    # what do you do here? return something 
    return first_guess 

你不能在所有分支

相關問題