You are currently viewing Take Multiple Inputs From The User In A Single Line Of Python Code

Take Multiple Inputs From The User In A Single Line Of Python Code

In Python, the input() function allows taking input from the user, and to provide a message with the input() function, we can prompt a string with it.

If we use a simple approach like a beginner then we would write a Python program like below to take multiple inputs.

There are some ways through which we can restrict the above code to a single line for taking multiple inputs from the user in Python. One-liners in Python are always powerful which helps us to write complex code in one line which in turn increases productivity and saves time.

We are going to see two methods through which we can achieve our goal

  • split() method
  • list comprehension

Using split() method

Generally, the split() method is used to split a Python string into a list but we can use it for taking multiple inputs from the user.

It will split the specified values in the input() function using a specified separator and if there is no specified separator then any whitespace is a separator.

Here we’ll use split() method with input() function.

input().split(separator, maxsplit)

  • separator: The string will separate at the specified separator. If it’s not provided then any whitespace is a separator.
  • maxsplit: A string will split into a maximum of a specified number of times. The default is -1, which means there is no limit.

Taking multiple inputs at a time

Output

We haven’t defined any separator and maxsplit parameters. Here we can use only three inputs because we’ve defined only three variables.

But there is a way to take unlimited inputs.

Taking unlimited inputs

Output

Taking inputs using separator and maxsplit

Output

In the first block of code, we specified the separator (,) and the inputs were separated by the commas hence we got the three separate outputs.

In the second block of code, we specified a separator and maxsplit=1 and we can see the output is split into two parts instead of getting three separate outputs.

Using list comprehension

It is the same process as we did in the first half of this article. Basically, we are going to use the split() but in the list comprehension method.

Taking multiple inputs at a time

Output

Using a separator

Output

We can use any type of separator whether it can be punctuation or letters.

Conclusion

One-liners can be very useful and helpful to enhance code quality as well as increase productivity. Well, we learned how to take multiple inputs from users in a single line of Python code instead of writing multiple lines of code.

We used the split() method which is primarily used for splitting the Python string into a list and then we used the list comprehension technique which offers a shorter syntax to define and create a list in Python.


That’s all for now

Keep Coding✌✌