42

This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python?

For instance, in C I can do something like this: scanf("%d %d", &var1, &var2). However, I can't figure out what the Python equivalent of that is. I figured it would just be something like var1, var2 = input("Enter two numbers here: "), but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did.

Does anyone out there know a good way to do this elegantly and concisely?

Jonta
  • 393
  • 5
  • 25

19 Answers19

60

The Python way to map

printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)

would be

var1, var2 = raw_input("Enter two numbers here: ").split()

Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,

Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line

var1, var2 = [int(var1), int(var2)]

Or you could use list comprehension

var1, var2 = [int(x) for x in [var1, var2]]

To sum it up, you could have done the whole thing with this one-liner:

# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]

# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
kizzx2
  • 18,775
  • 14
  • 76
  • 83
11

You can't really do it the C way (I think) but a pythonic way of doing this would be (if your 'inputs' have spaces in between them):

raw_answer = raw_input()
answers = raw_answer.split(' ') # list of 'answers'

So you could rewrite your try to:

var1, var2 = raw_input("enter two numbers:").split(' ')

Note that this it somewhat less flexible than using the 'first' solution (for example if you add a space at the end this will already break).

Also be aware that var1 and var2 will still be strings with this method when not cast to int.

ChristopheD
  • 112,638
  • 29
  • 165
  • 179
8

In Python 2.*, input lets the user enter any expression, e.g. a tuple:

>>> a, b = input('Two numbers please (with a comma in between): ')
Two numbers please (with a comma in between): 23, 45
>>> print a, b
23 45

In Python 3.*, input is like 2.*'s raw_input, returning you a string that's just what the user typed (rather than evaling it as 2.* used to do on input), so you'll have to .split, and/or eval, &c but you'll also be MUCH more in control of the whole thing.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • Oh noes. Please never do this: `input()` allows for arbitrary code execution. Just type `exit('pwned!')` at the input prompt and see what happens. – 9000 Mar 21 '17 at 20:18
  • @9000 I got a `ValueError` exception. That's perfect. So it's not that something harmful you meant. So no worries using `input()` now. – unclexo Jul 22 '18 at 06:44
6

If you need to take two integers say a,b in python you can use map function.
Suppose input is,

1
5 3
1 2 3 4 5

where 1 represent test case, 5 represent number of values and 3 represents a task value and in next line given 5 values, we can take such input using this method in PYTH 2.x Version.

testCases=int(raw_input())
number, taskValue = map(int, raw_input().split())
array = map(int, raw_input().split())

You can replace 'int' in map() with another datatype needed.

Rishabh Prasad
  • 349
  • 1
  • 3
  • 13
4

You have to use the split() method which splits the input into two different inputs. Whatever you pass into the split is looked for and the input is split from there. In most cases its the white space.

For example, You give the input 23 24 25. You expect 3 different inputs like

num1 = 23
num2 = 24
num3 = 25

So in Python, You can do

num1,num2,num3 = input().split(" ")
devDeejay
  • 5,494
  • 2
  • 27
  • 38
3

The solution I found is the following:


Ask the user to enter two numbers separated by a comma or other character

value = input("Enter 2 numbers (separated by a comma): ")

Then, the string is split: n takes the first value and m the second one

n,m = value.split(',')

Finally, to use them as integers, it is necessary to convert them

n, m = int(n), int(m)


E. Zavala
  • 31
  • 2
3

All input will be through a string. It's up to you to process that string after you've received it. Unless that is, you use the eval(input()) method, but that isn't recommended for most situations anyway.

input_string = raw_input("Enter 2 numbers here: ")
a, b = split_string_into_numbers(input_string)
do_stuff(a, b)
sykora
  • 96,888
  • 11
  • 64
  • 71
2

Check this handy function:

def gets(*types):
    return tuple([types[i](val) for i, val in enumerate(raw_input().split(' '))])

# usage:
a, b, c = gets(int, float, str)
  • 1
    Index access is not needed! `return tuple(parser(value) for (parser, value) in zip(types, raw_input(prompt).split(' ')))`. – 9000 Mar 21 '17 at 20:22
2

For n number of inputs declare the variable as an empty list and use the same syntax to proceed:

>>> x=input('Enter value of a and b').split(",")
Enter value of a and b
1,2,3,4
>>> x
['1', '2', '3', '4']
Dadep
  • 2,796
  • 5
  • 27
  • 40
2

You can do this way

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

OR

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

OR

MyList = list(map(int, input().split()))
a = MyList[0]
b = MyList[1]
vishwaraj
  • 487
  • 5
  • 5
1

The easiest way that I found for myself was using split function with input Like you have two variable a,b

a,b=input("Enter two numbers").split()

That's it. there is one more method(explicit method) Eg- you want to take input in three values

value=input("Enter the line")
a,b,c=value.split()

EASY..

1

This is a sample code to take two inputs seperated by split command and delimiter as ","


>>> var1, var2 = input("enter two numbers:").split(',')
>>>enter two numbers:2,3
>>> var1
'2'
>>> var2
'3'


Other variations of delimiters that can be used are as below :
var1, var2 = input("enter two numbers:").split(',')
var1, var2 = input("enter two numbers:").split(';')
var1, var2 = input("enter two numbers:").split('/')
var1, var2 = input("enter two numbers:").split(' ')
var1, var2 = input("enter two numbers:").split('~')

Jagannath Banerjee
  • 2,081
  • 1
  • 9
  • 7
1

Two inputs separated by space:

x,y=input().split()
Zeinab
  • 389
  • 4
  • 14
0
a,b=[int(x) for x in input().split()]
print(a,b)

Output

10 8

10 8

Siddharth jha
  • 598
  • 2
  • 15
0

In Python 3, raw_input() was renamed to input().

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So you can do this way

x, y = input('Enter two numbers separating by a space: ').split();
print(int(x) + int(y))

If you do not put two numbers using a space you would get a ValueError exception. So that is good to go.

N.B. If you need old behavior of input(), use eval(input())

unclexo
  • 3,691
  • 2
  • 18
  • 26
0

I tried this in Python 3 , seems to work fine .

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

print(a)

print(b)

Input : 3 44

Output :

3

44

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
0

This solution is being used for converting multiple string like ("22 44 112 2 34") to an integer list and you can access to the values in a list.

n = input("") # Like : "22 343 455 54445 22332"

if n[:-1] != " ":
n += " "

char = ""
list = []

for i in n :
    if i != " ":
        char += i
    elif i == " ":
        list.append(int(char))
        char = ""

print(list) # Be happy :))))
0

If we want to two inputs in a single line, the code is as follows

x, y = input().split(" ")

print(x, y)

when inputting the value we have to separate them with spaces between them because of .split(" ") call.

But these values are of type str. If we want to perform some arithmetic operations we have to convert the type of x and y as follows: int(x), int(y)

We can do this also with the help of list and map in python.

list1 = list(map(int, input().split()))
print(list1)

This list gives the elements of type int.

MegaIng
  • 7,361
  • 1
  • 22
  • 35
0

In short, using list comprehension and split()

Python 3:

var1, var2 = [int(num) for num in input("Enter two numbers separated by space: ").split()]

ADJ
  • 1,182
  • 2
  • 14
  • 26