2

我正在制作一个四人连接游戏,其中棋盘大小可以由玩家决定,同时忽略数字之间的空格量。

inp = input("Please input the size of the board youd like with the number of rows before "
            "the number of columns. If you would like to quit, please type quit").split()
while inp != "quit":
    nRows, nCols = inp

这种方法以前对我有用,但它不断导致:

ValueError: not enough values to unpack
4

3 回答 3

3

您收到错误是因为您只传递了一个值作为输入。相反,您应该像这样传递输入

1 2

input("msg").split() split默认将空格作为分隔符

所以你的代码是正确的,但你提供了错误的输入

于 2021-03-12T19:23:59.500 回答
0

当您按下回车键时,python 中的 input() 仅返回一个值,因此尝试从中创建两个值是行不通的。

您将需要单独定义这些值,而不是在一个 input() 语句中。

rRows = input("enter the number of rows")
nCols = input("enter the number of columns")
于 2021-03-12T19:15:35.517 回答
0

stringsplit()方法总是返回一个列表。因此,当用户输入一件事时,列表中只包含一项——这就是导致错误的原因。

在检查用户输入的内容时,您还需要考虑quit。下面的代码显示了如何处理这两种情况。

请注意,当循环退出时,两者都是字符串,nRowsnCols不是整数while——或者如果用户键入,则甚至不存在quit。)

while True:
    inp = input('Please input the size of the board you\'d like with the number of rows '
                'before\nthe number of columns. If you would like to quit, please type '
                '"quit": ').split()

    if inp == ["quit"]:
        break
    if len(inp) != 2:
        print('Please enter two values separated by space!')
        continue
    nRows, nCols = inp
    break
于 2021-03-12T19:54:14.420 回答