我有以下方法调用:

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]

===============>>#1 票数:3 已采纳

您遇到的问题是您的递归调用不会返回其结果。

因此,它打印出“ 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

===============>>#2 票数:0

这是因为代码中的某些路径不会以您显式返回任何内容而结束。

在递归地调用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

===============>>#3 票数: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

您不是在所有分支都返回

  ask by Deekor translate from so

未解决问题?本站智能推荐: