3

I am trying the code in the tutorial given here - http://www.vogella.com/tutorials/Python/article.html

He uses python 2.6 and I use 3.3. I don't know if that causes my problem.

My code -

def add(a,b):
    return a+b 

def addFixedValue(a):
    y = 5
    return y+a

print add(1,2)
print addFixedValue(1)

Error is -

    print add(1,2)
            ^
SyntaxError: invalid syntax

How do I correct it ?

5
  • print is a function in Python 3. Commented Mar 3, 2014 at 20:02
  • in python 3, I'm pretty sure print x becomes print(x) docs.python.org/3.0/whatsnew/3.0.html Commented Mar 3, 2014 at 20:02
  • 1
    Why am I getting a -1 for this ? If I was already knew py programming, I would not be asking my first py question. Commented Mar 3, 2014 at 20:04
  • 2
    Why would someone down-vote this question? It is well written, clear, provides complete source code, references, operating environment (Python version) specific error message and specific question! Seems to me it's ideal! (???) Commented Mar 3, 2014 at 20:04
  • 1
    @aldo because of the number of results for searching "python 3 print SyntaxError" here and elsewhere? Commented Mar 3, 2014 at 20:15

6 Answers 6

3

In Python versions before 3, print was a statement, not a function, so the code as you have it here is correct.

Starting with Python 3, print is now a function, so you need to wrap arguments in parentheses.

Python 1.x - 2.x:

print "This is a string"

Python 3.x:

print("This is a string")

The rationale behind this change is explained at http://legacy.python.org/dev/peps/pep-3105/

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I was also confused as to why there would be such a syntax change. I have never seen this in C, C++, C#, Java, SQL.
1

In Python 3, print is a function and thus requires parentheses:

print(add(1,2))
print(addFixedValue(1))

For more information, see Print is a Function.

Comments

1

In python 2.6, the following would work:

>>> print 'hi'
hi

However, print is a function in python 3.3, so surround it with parentheses:

>>> print(add(1,1))

Look here for more information, and here for the syntaxing from the docs.

Comments

1

If you're using python 3.3, print is no longer a statement, but a function. You thus need to put brackets around the printed object.

print(add(1,2))
print(addFixedValue(1))

Comments

0

In Python 3, print is a function

print(add(1,2))
print(addFixedValue(1))

Comments

0

You may try 2to3 for converting python 2.x program to python 3.x Documentation @ Automated Python 2 to 3 code translation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.