3

Recently I started studying about Python and I have come across one problem. Suppose you are given 3 space separated integers, say 4 5 6
When I use input() method and take the input, it is showing 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 guess, since it is in one line, it is assuming it to be a string, but finds out the integer at the location 2 (index starting from 0). I tried alternative method that I took the input as a string using raw_input() method and and wherever I find a number, I cast it as int and append it to the list.

Is there any better way of accomplishing the task?

thefourtheye
241k53 gold badges466 silver badges505 bronze badges
asked Jul 1, 2015 at 11:37

4 Answers 4

5

Function input() is interpreting your input as a Python code, I know, it's little odd. To get raw input (string containing user typed characters), just use raw_input() function instead.

answered Jul 1, 2015 at 11:40
Sign up to request clarification or add additional context in comments.

1 Comment

Just to add to this answer. If you use Python 3, you can simply use input. If you are starting off, you should probably start using Python 3 instead.
1

If you have just started studying then use python3. input line of your code would work fine. If you need to input 3 integers, you can use code like this:

x = input()
result = [ int(i) for i in x.split(' ')]
answered Jul 1, 2015 at 11:41

Comments

1

When you use input(), python tries to interpret the input, therefore getting confused when it finds a space.

You correctly suggested using raw_input().

inp = raw_input() # get raw input
lst = inp.split(" ") # split into list
num_lst = map(int, lst) # apply int() to all items
answered Jul 1, 2015 at 11:40

1 Comment

you can just use inp.split() and it will automatically do it for spaces.
0

try this:

a = []
a += map(int,raw_input("Enter the integers\n").split(" "))
print a
Racil Hilan
25.4k13 gold badges56 silver badges61 bronze badges
answered Sep 20, 2015 at 12:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.