从单个输入语句中分配多个值,忽略空格

问题描述 投票:0回答:3

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

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:没有足够的值来解压

python python-3.x input
3个回答
3
投票

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

这样的输入

1 2

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

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


0
投票

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

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

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

0
投票

字符串

split()
方法始终返回一个列表。因此,当用户输入一件事时,该列表仅包含一项 - 这就是导致错误的原因。

在检查用户输入的内容时,您还需要考虑

quit
。下面的代码显示了如何处理这两种情况。

注意,当

nRows
循环退出时,
nCols
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
© www.soinside.com 2019 - 2024. All rights reserved.