1

I have been using Python 2.7 for a while. Suddenly, I am getting errors with the print statement and it looks like I should now use Python 3.x syntax.

print 'hello world'
File "<ipython-input-462-d05d0c8adf1f>", line 1
   print 'hello world'
                  ^
SyntaxError: invalid syntax

print('hello world')
hello world

I double checked that I am still running a 2.x Python version:

import sys
print (sys.version)
2.7.12 |Anaconda 2.3.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]

The only change I did recently to my Python environment was to update matplotlib from 1.4 to 1.5, but being honest I can't say if the problem started from the exact moment of the update.

Any help would be appreciated (please let me know which other info on my system are needed)

FLab
  • 7,136
  • 5
  • 36
  • 69

1 Answers1

0

Are you using the print_function future import?

from __future__ import print_function

That function backports the new print syntax to Python 2 code. It is usually used if a codebase should be runnable both on Python 2 and 3.

Example:

>>> print 'hello'
hello
>>> from __future__ import print_function
>>> print 'hello'
  File "<stdin>", line 1
    print 'hello'
                ^
SyntaxError: invalid syntax
>>> print('hello')
hello

See the __future__ docs for more details.

In case you're not using that import yourself, you could test whether the problem only occurs in ipython or also in regular python, to narrow down the source of the problem.

Danilo Bargen
  • 18,626
  • 15
  • 91
  • 127
  • "a library you're using" - that would only affect the library, not the questioner, since future statements are module-local. – user2357112 Jul 08 '16 at 15:30
  • Can you please elaborate on that? I never used it in my scripts, so I would suspect this must have been contained in some of the libraries I am using. Would that be a problem or not? Simply restarting the kernel solved the problem, so it is very likely I must have used print_function future import – FLab Jul 08 '16 at 15:34
  • @FLab ah, you were using a jupyter/ipython notebook? is it possible that you pasted in some test code that contained the import in the past, after starting the kernel for the last time? Did you use some "magic" imports in the notebook (those starting with a % sign)? – Danilo Bargen Jul 08 '16 at 15:37