How to input multiple values from user in one line in Python?
For instance, in C we can do something like this:
// Reads two values in one line scanf("%d %d", &x;, &y;) |
One solution is to use raw_input() two times.
x, y = raw_input(), raw_input() |
Another solution is to use split()
x, y = raw_input().split() |
Note that we don’t have to explicitly specify split(‘ ‘) because split() uses any whitespace characters as delimiter as default.
One thing to note in above Python code is, both x and y would be of string. We can convert them to int using another line
x, y = [int(x), int(y)] # We can also use list comprehension x, y = [int(x) for x in [x, y]]
Below is complete one line code to read two integer variables from standard input using split and list comprehension
# Reads two numbers from input and typecasts them to int using # list comprehension x, y = [int(x) for x in raw_input().split()] |
# Reads two numbers from input and typecasts them to int using # map function x, y = map(int, raw_input().split()) |
Note that in Python 3, we use input() in place of raw_input().
This article is contributed by Abhishek Shukla. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Recommended Posts:
- Taking multiple inputs from user in Python
- Python | Get a list as input from user
- Take Matrix input from user in Python
- Returning Multiple Values in Python
- Python | Assign multiple variables with list values
- Read a file line by line in Python
- Python | Visualize missing values (NaN) values using Missingno Library
- Python User defined functions
- User-defined Exceptions in Python with Examples
- Python | Fetch your gmail emails from a particular user
- Fetch top 10 starred repositories of user on GitHub | Python
- Python | User groups with Custom permissions in Django
- Python | Merge Python key values to list
- Python OpenCV | cv2.line() method
- Python | Line (Canvas) in kivy
Improved By : dev_aditya


