3

I'm new to Python.

I was reading a tutorial online, the author used str = input(), and then he enters a sentence. After that, he get the input string stored in str. However, when I was trying str = input() in my python shell, it does not work. Here is the error:

>>> a = input()
test sentence

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    a = input()
  File "<string>", line 1
    test sentence
            ^
SyntaxError: unexpected EOF while parsing

Can you tell me why is the case?

0

4 Answers 4

4

The meaning of input has changed between Python 2 and Python 3. In Python 2, input actually evaluated whatever you entered as Python code. So when you enter something that is syntactically not correct in Python, then you get such an error. In addition, there is raw_input which just takes whatever input comes and returns it in a string.

Now because the evaluating input is not really that useful (and eval is evil), the behaviour of input got replaced by Python 2’s raw_input in Python 3.

The author of your tutorial most likely used Python 3, where input behaves like raw_input did in Python 2. If you use Python 2, just use raw_input instead.

Sign up to request clarification or add additional context in comments.

Comments

3

a = input() test sentence is not a valid code.

you can write comments with # character.

edit : what version of python are you using? try raw_input instead of input.

the difference between input and raw_input in python 2:

raw_input : reads whatever user wrote by newline and stores it into str

input : reads whatever user wrote and evalutes that input

raw_input became input in python 3.

Comments

2

Because you are using input(), it expects valid Python code. You get a SyntaxError because test sentence is not valid Python.

Therefore, try using raw_input() (which returns a string) OR do this:

>>> a = input()
'test sentence' # by entering it as a string, it is evaluable

References:

Comments

2

In Python 2, raw_input(...) will return whatever was typed in as a string. input(...) is equivalent to eval(raw_input(...)) (very dangerous!!). eval evaluates its argument as Python code and returns the result, so input expects properly-formatted Python code. You should never use input or eval in Python 2 as it is a security risk; use raw_input instead.

In Python 3, input(...) returns whatever was typed in as a string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.