42
votes

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?

18

18 Answers

58
votes

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()]
11
votes

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.

8
votes

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.

6
votes

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.

4
votes

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(" ")
3
votes

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)
3
votes

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)


2
votes

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)
2
votes

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']
2
votes

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]
1
votes

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
votes

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('~')

1
votes

Two inputs separated by space:

x,y=input().split()
0
votes
a,b=[int(x) for x in input().split()]
print(a,b)

Output

10 8

10 8

0
votes

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())

0
votes

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

0
votes

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
votes

if we want to two inputs in a single line so, the code is are as follows enter code here

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

print(x,y)

after giving value as input we have to give spaces between them because of split(" ") function or method.

but these values are of string type if to perform some arithmetic operations we have to convert the type of x,y are as follows int(x),int(y)

we can do this also with the help of list in python.enter code here

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

this list gives the elements in int type