How to enter 2 integers on one line in Python?

I wonder if it is possible to enter two or more integer numbers in one line of standard input. In C / C++ it is 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 will not 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 this?

+7
python input line
source share
2 answers

Separate the entered text in a space:

 a, b = map(int, input().split()) 

Demo:

 >>> a, b = map(int, input().split()) 3 5 >>> a 3 >>> b 5 
+14
source share

If you are using Python 2 then Martijn's answer is not working. Use instead:

 a, b = map(int, raw_input().split()) 
+2
source share

All Articles