【问题标题】:Function is returning None when it should be returning True or False [duplicate]函数在应该返回 True 或 False 时返回 None [重复]
【发布时间】:2020-06-25 00:37:38
【问题描述】:

我正在为 Connect 4 游戏制作获胜检查功能。网格是 7x6,连续 4 个图块应该导致函数返回 True,否则返回 False。相关代码如下:

grid=[[" O ","   ","   ","   ","   ","   "],["   "," O ","   ","   ","   ","   "],["   ","   "," O ","   ","   ","   "],["   ","   ","   "," O ","   ","   "],["   ","   ","   ","   "," O ","   "],["   ","   ","   ","   ","   "," O "],["   ","   ","   ","   ","   ","   "]]
#2D array for grid

typetofunct={"left":"x-1,y,'left'","right":"x+1,y,'right'","up":"x,y+1,'up'","down":"x,y-1,'down'","topleft":"x-1,y+1,'topleft'","topright":"x+1,y+1,'topright'","downleft":"x-1,y-1,'downleft'","downright":"x+1,y-1,'downright'"}
def check(x,y,checktype,count):
    if not ((x==0 and (checktype=="left" or checktype=="topleft" or checktype=="bottomleft")) or (x==6 and (checktype=="right" or checktype=="bottomright" or checktype=="topright")) or (y==0 and (checktype=="down" or checktype=="downleft" or checktype=="downright")) or (y==5 and (checktype=="up" or checktype=="topleft" or checktype=="topright"))): #doesn't check if it's on a boundary
        print("Checked {0}".format(checktype))
        if grid[x][y]!="   ":
            print(count)
            count+=1
            if count>=4:
                print("True reached")
                return True
            else:
                print("Looping")
                return exec("check({0},count)".format(typetofunct.get(checktype)))
                #recurs the function, has to get it from a dictionary according to string
        else:
            print("Grid was empty")
            return count>=4
    else:
        print("Out of bounds")
        return False
print(check(0,0,"topright",0))

这应该是打印:

Checked topright
0
Looping
Checked topright
1
Looping
Checked topright
2
Looping
Checked topright
3
True reached
True

但我得到的是:

Checked topright
0
Looping
Checked topright
1
Looping
Checked topright
2
Looping
Checked topright
3
True reached
None

据我所知,这个函数应该只返回 True 或 False。请帮忙。

【问题讨论】:

标签: python


【解决方案1】:

return exec("check({0},count)".format(typetofunct.get(checktype))) 是返回的 None

>>> a = exec("print('ciao')")
ciao
>>> a is None
True
>>>

【讨论】:

  • 我为什么投了反对票?
【解决方案2】:

问题是函数exec 没有返回任何东西,即使它里面的函数返回。所以这行:

return exec("check({0},count)".format(typetofunct.get(checktype)))

将始终返回None

为什么不直接调用函数本身,而不使用exec

return check(typetofunct.get(checktype),count)

【讨论】:

  • 问题是我从 typetofunct 获得了多个参数,这就是我使用 exec() 添加两个参数的原因。不过 eval() 有效。
  • @BusterTornado 我明白了。那么,为什么不在字典中使用元组而不是字符串呢?这将使单独访问每个元素变得更加容易。
  • 因为 x 和 y 只在函数中定义,而不在字典中定义,所以在代码开头尝试定义字典时会引发错误。我可以在函数的开头定义字典,但是在函数中只使用 eval() 比在每次循环时重新定义字典更有效。
猜你喜欢
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多