停止while循环从一遍又一遍?Python



我有一个问题,我的代码一遍又一遍地重复一个语句,当我不希望它。

下面是我的代码:
def gameMake():
    while emptySp(): #already written (checks if the space is available for the user to put in their token)

        print("Player 1")
        mycol = input("Please choose a column (1-" + str(columns))
        if coluser == columns:
            mycol = input("Please choose a column to place your piece in (1-" + str(columns))
        elif:
            rowuse = rows

            while x >= 1:
                if board[x][coluser] == board[r][c]
                    board[x][coluser] == PONE #PONE = "o" (the token)

                else:
                    i = 0
                    i = i + 1

输出的例子和我得到的:(板输入是5x5)

Player 1 
Please choose a column (1-5): 1
Player 1 
Please choose a column (1-5): 2
Player 1 
Please choose a column (1-5):3
Player 1 
Please choose a column (1-5): 4
Player 1 
Please choose a column (1-5): 5

IndexError: list index out of range

代码应该接受数字1-5作为有效的列号,然后使用我已经创建的board函数打印出当前的board !如果是1-5以外的数字,它应该重新提示用户!我的代码出了什么问题?为什么会出现索引错误?

谢谢!

这里的问题是,您没有检查数字是否在1- x的范围内,您只是检查数字是否>= 1。

您需要更新while语句以读取while x >= 1 and x <= columns:

您可能还想使用a try/except块来提示输入mycol = input("Please..。我提出这个是因为目前你的脚本将失败,如果有人输入A-Z或任何其他特殊字符。

从您显示的示例输入/输出中,似乎您总是在最内部的if子句中结束。这里,board[x][coluser] == PONE执行的是比较,而不是赋值,因此它的计算结果为真或假,但不改变程序其余部分的任何内容。所以emptySp()总是返回true,因为没有任何改变。其次,什么是"#Check for any win with win function"?win函数是什么?同样,在if子句中,没有任何部分的代码被改变,所以无论导致emptySp()第一次求值为true的是什么,都将继续保持不变。

最新更新