簡體   English   中英

為什么我的方法返回None?

[英]Why is my method returning 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]

您遇到的問題是您的遞歸調用不會返回其結果。

因此,它打印出“ of for loop…”,然后進行遞歸調用。 然后,該遞歸調用成功返回了某些內容……但是外部調用忽略了該內容,並且掉到了最后,這意味着您得到None

只需在調用firstGuess之前添加return firstGuess

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)

這仍然留下一條路徑,在該路徑中您什么也不返回(如果您進入“循環外”,然后是len(first_guess) > NPEGS )……但是您沒有任何邏輯可做任何有用的事情。 如果您認為這永遠不會發生,則可能需要添加某種assertraise

這是因為代碼中的某些路徑不會以您顯式返回任何內容而結束。

在遞歸地調用firstGuess ,應該執行return firstGuess(...)嗎? 但是,仍然有可能您掉進去並且什么也沒退還。 您應該添加最終return first_guess最后陳述后, if語句。

嘗試這個:

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

將最后兩行更改為

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

您不是在所有分支都返回

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM