input() on python 2.7.5 vs 3.3.2

Chris Angelico rosuav at gmail.com
Thu Dec 12 09:53:34 EST 2013


On Fri, Dec 13, 2013 at 1:45 AM,  <stephen.boulet at gmail.com> wrote:
> Can someone explain? Thanks.
>
> Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> x = input()
> Hello there
>>>> print(x)
> Hello there
>
> Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> x = input()
> Hello there
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<string>", line 1
>     Hello there
>               ^
> SyntaxError: unexpected EOF while parsing

It's very simple: The input() function in Python 2.x is a very
dangerous one - it's equivalent to eval(input()) in Python 3. The
equivalent function in Python 2 is called raw_input. For safety and
compatibility, just do this at the beginning of your interactive
session or the top of your script:

input = raw_input

or, in a way that'll work in Python 3 as well, with no changes:

try:
    input = raw_input
except NameError:
    pass

After that, you can safely call input() and get back a string.

ChrisA



More information about the Python-list mailing list