10

I have the following python code:

print 'This is a simple game.'
input('Press enter to continue . . .')
print 'Choose an option:'

...

But when I press Enter button, I get the following error:

Traceback (most recent call last):
  File "E:/4.Python/temp.py", line 2, in <module>
    input('Press enter to continue . . .')
  File "<string>", line 0
    
   ^
SyntaxError: unexpected EOF while parsing

P.S. I am using python IDLE version 2.6 on Windows 7.


Related problem in IPython: Why does the IPython REPL tell me "SyntaxError: unexpected EOF while parsing" as I input the code?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Azad Salahli
  • 876
  • 3
  • 14
  • 30

4 Answers4

23

For Python 2, you want raw_input, not input. The former will read a line. The latter will read a line and try to execute it, not advisable if you don't want your code being corrupted by the person entering data.

For example, they could do something like call arbitrary functions, as per the following example:

def sety99():
    global y
    y = 99

y = 0
input ("Enter something: ")
print y

If you run that code under Python 2 and enter sety99(), the output will 99, despite the fact that at no point does your code (in its normal execution flow) purposefully set y to anything other than zero (it does in the function but that function is never explicitly called by your code). The reason for this is that the input(prompt) call is equivalent to eval(raw_input(prompt)).

See here for the gory details.

Keep in mind that Python 3 fixes this. The input function there behaves as you would expect.

wovano
  • 4,543
  • 5
  • 22
  • 49
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    Actually, you can't *assign* anything in `eval`. However, you can call whatever destructive method you'd like, so it's hardly any better. –  Feb 17 '11 at 09:09
  • Or, you want to use Python 3, where `input()` does what the Python 2 `raw_input()` did. – S.Lott Feb 17 '11 at 10:53
4

In Python 2, input() strings are evaluated, and if they are empty, an exception is raised. You probably want raw_input() (or move on to Python 3).

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
3

In Python 2.x, input() is equivalent to eval(raw_input()). And eval gives a syntax error when you pass it an empty string.

You want to use raw_input() instead.

dan04
  • 87,747
  • 23
  • 163
  • 198
2

If you use input on Python 2.x, it is interpreted as a Python expression, which is not what you want. And since in your case, the string is empty, an error is raised.

What you need is raw_input. Use that and it will return a string.

user225312
  • 126,773
  • 69
  • 172
  • 181