Syntax error on print with Python 3

PythonPython 3.x

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

print("Hello World")

Solution 2 - Python

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!')

Solution 3 - Python

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?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionScottView Question on Stackoverflow
Solution 1 - PythonUnknownView Answer on Stackoverflow
Solution 2 - PythonbrianzView Answer on Stackoverflow
Solution 3 - PythonPandikunta Anand ReddyView Answer on Stackoverflow