Python data input
I recently started learning Python and I ran into one problem. Suppose you are given integers separated by a space, say 4 5 6
When I use the input () method and take input, it shows me an error.
Traceback (most recent call last):
File "P_Try.py", line 1, in <module>
x= input();
File "<string>", line 1
4 5 6
^
SyntaxError: invalid syntax
I think since it is on the same line it assumes it is a string, but it detects an integer at location 2 (index starting at 0). I tried an alternative method that I took as a string using the raw_input () method, and wherever I find a number, I passed it as an int and added it to the list.
Is there a better way to accomplish the task?
The function input()
interprets your input as Python code, I know this is a little strange. To get the original input (a string containing user-entered characters), use a function instead raw_input()
.
When you use input()
, python tries to interpret the input, so it gets confused when it finds a space.
You suggested using correctly raw_input()
.
inp = raw_input() # get raw input
lst = inp.split(" ") # split into list
num_lst = map(int, lst) # apply int() to all items
If you've just started learning, use python3. input
the line of your code will work fine. If you need to enter 3 integers, you can use the following code:
x = input()
result = [ int(i) for i in x.split(' ')]
try this:
a = []
a += map(int,raw_input("Enter the integers\n").split(" "))
print a