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?
The Python way to map
printf("Enter two numbers here: "); scanf("%d %d", &var1, &var2)
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
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()]