Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to input 2 integers in one line in Python?

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?

like image 308
enedil Avatar asked Apr 23 '14 19:04

enedil


People also ask

How do you print two integers on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do you take a list of inputs in one line in Python?

To take list input in Python in a single line use input() function and split() function. Where input() function accepts a string, integer, and character input from a user and split() function to split an input string by space.


2 Answers

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
like image 135
Martijn Pieters Avatar answered Oct 12 '22 05:10

Martijn Pieters


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

a, b = map(int, raw_input().split())
like image 38
Dhruv Bhagat Avatar answered Oct 12 '22 05:10

Dhruv Bhagat