Assigning multiple values from a single input statement disregarding whitespace

161 Views Asked by At

I'm making a connect-four game where the board size can be decided by the players while ignoring the amount of spaces between the numbers.

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

This method has worked for me previously, but it keeps causing a:

ValueError: not enough values to unpack
3

There are 3 best solutions below

1
EXODIA On BEST ANSWER

You are getting error because you're passing only one value as input. Instead, you should pass input like

1 2

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

So your code is correct but you're providing wrong input

0
this is a good name On

input() in python returns only a single value when you press enter, so trying to create two values out of it wont work.

you will need to define the values seperately rather then in one input() statement.

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

The string split() method always returns a list. So when the user enters on one thing that list only contains one item — which is what is causing the error.

You will also need to take thing into consideration when checking it the user typed in quit. The code below shows how to handle both of the conditions.

(Note the both nRows and nCols will be strings, not integers when the while loop exits — or not even exist if the user types 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