为什么我的方法返回None?

时间:2013-04-17 22:10:54

标签: python

我有以下方法调用:

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 个答案:

答案 0 :(得分:3)

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

因此,它打印出“for for of loop ...”,然后它进行递归调用。那个递归调用然后成功地返回了一些东西......但是外部调用忽略了它并且从结束处掉了下来,这意味着你得到了None

只需在致电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)

这仍然留下一条你不返回任何东西的路径(如果你进入“for for for循环”,然后是len(first_guess) > NPEGS)......但你没有任何逻辑可以做任何有用的事情。如果您认为可能永远不会发生,可能需要添加某种assertraise

答案 1 :(得分: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

答案 2 :(得分: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

你没有回到所有分支