274

Why do I receive a syntax error when printing a string in Python 3?

>>> print "hello World"
  File "<stdin>", line 1
    print "hello World"
                      ^
SyntaxError: invalid syntax
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Scott
  • 11,046
  • 10
  • 51
  • 83
  • 18
    hint: for compatibility code in python 2.7+ put this into the beginning of the module: `from __future__ import print_function` – Yauhen Yakimovich Aug 12 '13 at 13:12
  • ...import print_function doesn't seem to work, do you need to change something in the print statements? or should the import do it? – RASMiranda Mar 28 '14 at 11:18
  • 5
    For the record, this case will be getting a custom error message in Python 3.4.2: https://stackoverflow.com/questions/25445439/what-does-syntaxerror-missing-parentheses-in-call-to-print-mean-in-python/ – ncoghlan Aug 22 '14 at 11:01
  • Closing this as a dupe of the other post by @ncoghlan, because 1. It has a more comprehensive answer 2. It is updated to match the latest error. – Bhargav Rao Jun 20 '16 at 16:27
  • 1
    2to3 is a Python program that reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code Further informations can be found here: [Python Documentation: Automated Python 2 to 3 code translation ](https://docs.python.org/2/library/2to3.html) – Oliver Sievers Jul 19 '15 at 10:21

3 Answers3

339

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")
NSNoob
  • 5,548
  • 6
  • 41
  • 54
Unknown
  • 45,913
  • 27
  • 138
  • 182
49

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')
NSNoob
  • 5,548
  • 6
  • 41
  • 54
brianz
  • 7,268
  • 4
  • 37
  • 44
30

Because in Python 3, print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement. So you have to write it as

print("Hello World")

But if you write this in a program and someone using Python 2.x tries to run it, they will get an error. To avoid this, it is a good practice to import print function:

from __future__ import print_function

Now your code works on both 2.x & 3.x.

Check out below examples also to get familiar with print() function.

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Source: What’s New In Python 3.0?

TheTechRobo the Nerd
  • 1,249
  • 15
  • 28
Chillar Anand
  • 27,936
  • 9
  • 119
  • 136