从单个输入语句中分配多个值而不考虑空格

Assigning multiple values from a single input statement disregarding whitespace

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

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

input() in python returns 当您按 enter 键时只有一个值,因此尝试从中创建两个值是行不通的。

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

rRows = input("enter the number of rows")
nCols = input("enter the number of columns")

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

这样的输入

1 2

input("msg").split() split by default takes space as separator

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

字符串split()方法总是returns一个列表。因此,当用户输入一件事时,列表只包含一个项目——这就是导致错误的原因。

在检查用户输入 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