Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Taking multiple inputs from user in Python
In this tutorial, we are going to learn how to take multiple inputs from the user in Python.
The data entered by the user will be in the string format. So, we can use the split() method to divide the user entered data.
Taking Multiple String Inputs
Let's take multiple strings from the user using split() ?
# taking the input from the user
strings = input("Enter multiple names space-separated:- ")
# splitting the data
strings = strings.split()
# printing the data
print(strings)
The output of the above code is ?
Enter multiple names space-separated:- Python JavaScript Django React ['Python', 'JavaScript', 'Django', 'React']
Taking Multiple Integer Inputs
What if we want to take multiple numbers as input? We can convert each input to an integer using the map() and int() functions ?
# taking the input from the user
numbers = input("Enter multiple numbers space-separated:- ")
# splitting the data and converting each string number to int
numbers = list(map(int, numbers.split()))
# printing the data
print(numbers)
The output of the above code is ?
Enter multiple numbers space-separated:- 1 2 3 4 5 [1, 2, 3, 4, 5]
Using One-Line Input
You can combine input, split, and conversion in a single line for cleaner code ?
# Taking multiple integers in one line
numbers = list(map(int, input("Enter numbers: ").split()))
print("Numbers:", numbers)
# Taking multiple floats in one line
floats = list(map(float, input("Enter decimals: ").split()))
print("Decimals:", floats)
The output of the above code is ?
Enter numbers: 10 20 30 Numbers: [10, 20, 30] Enter decimals: 1.5 2.7 3.9 Decimals: [1.5, 2.7, 3.9]
Unpacking Multiple Inputs
When you know the exact number of inputs, you can unpack them directly into variables ?
# Unpacking three string inputs
name, age, city = input("Enter name, age, city: ").split()
print(f"Name: {name}, Age: {age}, City: {city}")
# Unpacking three integer inputs
a, b, c = map(int, input("Enter three numbers: ").split())
print(f"Sum: {a + b + c}")
The output of the above code is ?
Enter name, age, city: John 25 NYC Name: John, Age: 25, City: NYC Enter three numbers: 5 10 15 Sum: 30
Comparison
| Method | Best For | Example |
|---|---|---|
split() |
Strings | input().split() |
map(int, split()) |
Integers | list(map(int, input().split())) |
| Unpacking | Fixed number of inputs | a, b = input().split() |
Conclusion
Use split() for multiple string inputs and map() with int() or float() for numeric inputs. Unpacking works best when you know the exact number of inputs expected.
