![]() |
VOOZH | about |
While taking a single input from a user is straightforward using the input() function, many real world scenarios require the user to provide multiple pieces of data at once. This article will explore various ways to take multiple inputs from the user in Python.
One of the simplest ways to take multiple inputs from a user in Python is by using the input() function along with the split() method. The split() method splits a string into a list based on a specified separator (by default, it uses whitespace).
Output:
values: 5 6 7
5
6
7
Let's take a look at other cases of taking multiple inputs from user in python:
If we want to ask the user for multiple values on a single line, we can use list comprehension combined with the input() function and split() to break the input into individual components. Also we can take inputs separated by custom delimiter which is comma in the below example.
Output :
5 6 7 8
['5', '6', '7', '8']
Explanation:
Note: You can replace comma with any delimiter if you want to take inputs separated by space.
If you need to collect multiple inputs in a single line and convert them into integers (or another data type), the map() function is useful. The map() function applies a specified function to each item in an iterable.
Output:
5 6 7 8 9
[5, 6, 7, 8, 9]
input() to take a single line of input.split() method divides the string into a list of substrings.map(int, ...) converts each element in the list to an integer.If you want to collect multiple inputs from the user one at a time, you can use a loop. This is particularly useful when you need to collect an arbitrary number of inputs or perform validation on each input.
Explanation: