How to take either multiple or single input on one line from Python

Question:

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?

Asked By: kwl1234

||

Answers:

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]….

What is happening here:
input() is used to take the input and store it in the memory buffer before allocating to the variable
split() takes the value in the variable or input buffer and split it based on a white space
input() is similar to input(" ")
The above code can be also written as

lst = input()
lst = lst.split()```
Answered By: pavan sai

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
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.