In Python programming, it’s often necessary to take multiple inputs from the user for certain programs or calculations. This could be a list of numbers, words, names, etc. This tutorial will guide you through methods on how to take multiple inputs in Python.
Method 1: Using Split()
One of the simplest methods for accepting multiple inputs from a user in Python is by using the split() function. This function splits the input into multiple parts, based on the delimiters (spaces, commas, etc.) you provide.
1 2 3 4 5 |
x, y, z = input("Enter a three value: ").split() print("Total number of students: ", x) print("Number of boys: ", y) print("Number of girls: ", z) |
Method 2: Using List Comprehension
List comprehension is a concise way to create lists in Python. It provides a more syntactically appealing method to create lists based on existing lists.
1 2 |
x = [int(x) for x in input("Enter multiple value: ").split()] print("Number of list is: ", x) |
Method 3: Using map() function
The map() function applies a given function to each item in an iterable (list, tuple etc.) and returns a list of the results. It is often utilized when we want to convert the input string into integers or floats.
1 2 |
x = list(map(int, input("Enter a multiple value: ").split())) print("List of students: ", x) |
The Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Method 1 x, y, z = input("Enter a three value: ").split() print("Total number of students: ", x) print("Number of boys: ", y) print("Number of girls: ", z) # Method 2 x = [int(x) for x in input("Enter multiple value: ").split()] print("Number of list is: ", x) # Method 3 x = list(map(int, input("Enter a multiple value: ").split())) print("List of students: ", x) |
Conclusion
These are three of the many ways you can accept multiple inputs in Python. Each method has its own advantages. For instance, the split() function is quick and easy but only returns strings.
On the other hand, List Comprehension and map() function can return integers or floats, offering more flexibility. The decision of which method to use largely depends on the specific requirements of your program.