Question

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?

Was it helpful?

Solution

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

OTHER TIPS

If you are using Python 2, then the answer provided by Martijn does not work. Instead,use:

a, b = map(int, raw_input().split())
x,y = [int(v) for v in input().split()]
print("x : ",x,"\ty: ",y)

In python, every time we use input() function it directly switches to the next line. To use multiple inline inputs, we have to use split() method along with input function by which we can get desired output.

a, b = [int(z) for z in input().split()]
print(a, b)

Input:

3 4

Output:

3 4
x, y = int(input()),  int(input())
print("x : ",x,"\ty: ",y)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top