Home > Software design >  How to take either multiple or single input on one line from Python
How to take either multiple or single input on one line from Python

Time:09-05

To accept multiple inputs on one line, I know you can do something like:

a, b = input().split()

And if the user were to only type 1 input, they would come across a ValueError:

"ValueError: not enough values to unpack (expected 2, got 1)"

Therefore is there a way of allowing the user the choice to write either 1 or both inputs so that if the user were to only have 1 input, the variable b would be forgotten or replaced with a placeholder?

CodePudding user response:

Honestly, the best is probably to collect the list and act depending on its length.

Now, if you really want to handle at least 1, or 2 (or more), you could use packing/unpacking:

a, *b = input().split()

print(f'first variable is {a}')
print(f'there is {"a" if b else "no"} second variable')
if b:
    print(f'second variable is {b[0]}')

Example 1:

x y

first variable is x
there is a second variable
second variable is y

Example 2:

x

first variable is x
there is no second variable

default value:

a, *b = input().split()
b = next(iter(b), 'default')
print('variables:', a, b)

Example 1:

x y

variables: x y

Example 2:

x

variables: x default

CodePudding user response:

Take the input as a list i.e.,

lst = input().split()

So you won't get value error you can later make changes on the user input with the help of indexing ... lst[0]....

  • Related