Two values from one input in python? [duplicate]
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?
19 Answers 19
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 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()]
Read two variables in a single line with Python [duplicate]
I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables? I’m looking for the equivalent of:
One way I am able to achieve this is to use raw_input() and then split what was entered. Is there a more elegant way? This is not for live use. Just for learning..
9 Answers 9
No, the usual way is raw_input().split()
In your case you might use map(int, raw_input().split()) if you want them to be integers rather than strings
Don’t use input() for that. Consider what happens if the user enters
Note that starting with Python 3.0, raw_input was renamed to input . (And to get the original behavior of input , use eval(input) .)
Yes, the obvious behaviour in 3 is much better, but I wish they had dropped some warnings into 2.6 about those changes. I guess I need to study the upgrade guide
no it should be int(input() , if you do eval(input()) in python3 you get a very dangerous backdoor because the user will be able to execute any python statement (even os.system) with your user’s rights.
@dialloliogn: read again. I made a general remark about how to get Python 2’s input behavior in Python 3.
You can also read from sys.stdin
import sys a,b = map(int,sys.stdin.readline().split())
I am new at this stuff as well. Did a bit of research from the python.org website and a bit of hacking to get this to work. The raw_input function is back again, changed from input. This is what I came up with:
i,j = raw_input("Enter two values: ").split() i = int(i) j = int(j)
Granted, the code is not as elegant as the one-liners using C’s scanf or C++’s cin. The Python code looks closer to Java (which employs an entirely different mechanism from C, C++ or Python) such that each variable needs to be dealt with separately.
In Python, the raw_input function gets characters off the console and concatenates them into a single str as its output. When just one variable is found on the left-hand-side of the assignment operator, the split function breaks this str into a list of str values .
In our case, one where we expect two variables, we can get values into them using a comma-separated list for their identifiers. str values then get assigned into the variables listed. If we want to do arithmetic with these values, we need to convert them into the numeric int (or float) data type using Python’s built-in int or float function.
I know this posting is a reply to a very old posting and probably the knowledge has been out there as «common knowledge» for some time. However, I would have appreciated a posting such as this one rather than my having to spend a few hours of searching and hacking until I came up with what I felt was the most elegant solution that can be presented in a CS1 classroom.
Taking multiple integers on the same line as input from the user in python
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box. How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number. enter second number.
Yes, I figured that. I’m still surprised because raw_input should just write the prompt to sys.stdout and read the input from sys.stdin , and those are usually a terminal, another program’s output or a file. If there’s GUI happening when you do it, that’d be very unusual enviroment.
19 Answers 19
You can then use ‘a’ and ‘b’ separately.
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ") input_list = user_input.split(',') numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
Or if you are collecting many numbers, use a loop
num = [] for i in xrange(1, 10): num.append(raw_input('Enter the %s number: ')) print num
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it’s not what you wanted, but I already wrote this answer before I realized that. So, I’m going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop’s level.
data="" while 1: data=raw_input("Command: ") if data in ("test", "experiment", "try"): data2="" while data2=="": data2=raw_input("Which test? ") if data2=="chemical": print("You chose a chemical test.") else: print("We don't have any " + data2 + " tests.") elif data=="quit": break else: pass
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',') #strip is used to remove the white space. Not mandatory all_numbers = [int(x.strip()) for x in user_input] for i in all_numbers: print(i)
- a, b, c = input().split() # for space-separated inputs
- a, b, c = input().split(«,») # for comma-separated inputs
whenever you want to take multiple inputs in a single line with the inputs seperated with spaces then use the first case .And when the inputes are seperated by comma then use the seconfd case . You implement this to shell or any ide and see the working ..@MittalPatel
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
The best way to practice by using a single liner,
Syntax:
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
List_of_input=list(map(int,input (). split ())) print(List_of_input)
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ') second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second . For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second) print('The product of the two is ' + str(product))
Thats right but isnt this going to open up two boxes. how can i enter both numbers in one box? like embedding both raw_input commands into one dialogue box at the same time
@user899714 In the default cpython environment, raw_input has no graphical user interface. You seem to be using a graphical/educational Python environment. Can you tell us the name of that environment?
Actually i haven’t used one yet. i was wondering if i could enhance the look of how i take input from user without getting into the hassle of using a graphical environment just by modifying/changing raw_input command. But i guess it isn’t possible.
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ‘,’.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')] print items
import sys for line in sys.stdin: j= int(line[0]) e= float(line[1]) t= str(line[2])
For details, please review,
Split function will split the input data according to whitespace.
data = input().split() name=data[0] id=data[1] marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = [] # endless loop, exit condition within while True: inputstr = input('Enter another string, or nothing to quit: ') if inputstr: strings.append(inputstr) else: break
This is Python 3 code; for Python 2, you would use raw_input instead of input .
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can’t for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines: strings = [line.rstrip('\n') for line in lines]