在循环中停止而不是一遍又一遍?蟒蛇

时间:2016-11-16 22:09:08

标签: python while-loop

我遇到一个问题,我的代码在我不想要的时候反复重复声明。

这是我的代码:

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作为有效列号,然后使用我已创建的板功能打印出当前板!如果它的任何数字不是1-5,它应该重新提示用户!我的代码出了什么问题?为什么会出现索引错误?

谢谢!

2 个答案:

答案 0 :(得分:0)

这里的问题是你没有检查数字是否在1-X范围内,你只是检查数字是否> = 1.

您可能希望更新while语句以阅读while x >= 1 and x <= columns:

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

答案 1 :(得分:0)

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