即使条件为假,While 循环仍在运行

时间:2021-07-27 10:24:04

标签: python loops while-loop

我一直在做井字游戏项目,但是有一个问题:

intro()

row_top = [' ','|',' ','|',' ']
line = ['-','-','-','-','-']
row_mid = [' ','|',' ','|',' ']
row_low = [' ','|',' ','|',' ']

default = (' ' in row_top or ' ' in row_mid or ' ' in row_low)

p1 = True

while default:

    while p1 :

        p1c = int(input('P1 turn! insert the position you want to place the marker:'))

        if inserter_1(p1c) != 'Error':
            display()
            p1 = False

    while not p1:

        p2c = int(input('P2 turn! insert the position you want to place the marker:'))

        if inserter_2(p2c) != 'Error':
            display()
            p1 = True

winner_check()

inserter() 函数将空格字符串的值更改为“X”或“O”,并且 display() 函数打印出棋盘。

即使 display() 函数显示板已填满(这意味着所有行中都没有“ ”),它仍然要求输入。

真正令人困惑的是默认条件绝对是错误的,我什至尝试添加一个从 1 到 9 的数字列表,并在每次玩家输入时删除一个数字,但它仍然不工作。

任何帮助将不胜感激。非常感谢!

2 个答案:

答案 0 :(得分:3)

这里有一个小测验,你认为这个表达式多久被评估一次? 当代码达到默认 = 时,它是一次。 您似乎认为每次都会重新评估默认值,但它只是永远保持 True,因为它永远不会改变。 尝试用 while 循环中使用的表达式替换 default

答案 1 :(得分:0)

关于“”有一些边缘情况。我在 jupyter notebook 上测试了“default”:

enter image description here

现在注意 row_top[0]。它没有填充但返回false

enter image description here

看看这个。应该返回true但返回false。我将 default 的条件从 ' ' 更改为 '' 以了解细微的变化。

enter image description here

另一种边缘情况:

enter image description here

在操纵状态时,是在破坏逻辑