How to input 2 integers in one line in Python?
51,540
Solution 1
Split the entered text on whitespace:
a, b = map(int, input().split())
Demo:
>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5
Solution 2
If you are using Python 2, then the answer provided by Martijn does not work. Instead,use:
a, b = map(int, raw_input().split())
Comments
-
enedil over 2 years
I wonder if it is possible to input two or more integer numbers in one line of standard input. In
C
/C++
it's easy:C++
:#include <iostream> int main() { int a, b; std::cin >> a >> b; return 0; }
C
:#include <stdio.h> void main() { int a, b; scanf("%d%d", &a, &b); }
In
Python
, it won't work:enedil@notebook:~$ cat script.py #!/usr/bin/python3 a = int(input()) b = int(input()) enedil@notebook:~$ python3 script.py 3 5 Traceback (most recent call last): File "script.py", line 2, in <module> a = int(input()) ValueError: invalid literal for int() with base 10: '3 5'
So how to do it?
-
pepr about 10 years+1. This is the nice example of why
map
and the like functions should remain in Python 3. I would only add the, *rest
to the left side to make it more robust. The non-map version with the list comprehension is also possible, but it is not that clean:a, b, *rest = [int(e) for e in input().split()]
. -
Samuel Bushi over 8 years
input()
still didn't work for me in Pycharm ( Python 2.7 ). Change it toraw_input
to make it work. -
Martijn Pieters over 8 years@blumonkey: this question is about Python 3. For Python 2, you indeed need to use
raw_input
. -
deppfx almost 7 years@MartijnPieters Is it possible to take the same inputs from multi lines? Something like
a, b = map(int, input().split("\n"))
? -
Martijn Pieters almost 7 years@deppfx:
input()
can't take multiple lines. Use a loop. -
enedil over 6 yearsSorry guy, the tag said "python 3". Your code is valid in Python 2. input in py3 is exactly raw_input from py2.
-
Shantanu about 5 years@MartijnPieters how to use the split() function in the list?
-
Martijn Pieters about 5 years@ShantanuDwivedi: I'm not sure what you are asking.
str.split()
is a string method, if you have a list of strings, then you need a loop (either an explicitfor
loop over the list, or a list comprehension). -
Shantanu about 5 years@MartijnPieters how can i use split() function inside the loop?
-
Martijn Pieters about 5 years@ShantanuDwivedi: that's too broad to answer in comments, because it depends entirely on what you are splitting and what you are doing with the values. Perhaps you can do some research on this with searching Stack Overflow? There are many, many questions and answers on the subject here.
-
Gino Mempin over 2 yearsThis prompts for input in 2 separate lines. The question was entering 2 integers in 1 line.
-
Tadhg McDonald-Jensen over 2 yearsit is asking for one line of input not one line of code :)