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 ?

InTheSkies
  • 999
  • 2
  • 7
  • 13
  • `print` is a function in Python 3. – Ashwini Chaudhary Mar 03 '14 at 20:02
  • in python 3, I'm pretty sure print x becomes print(x) http://docs.python.org/3.0/whatsnew/3.0.html – justin cress Mar 03 '14 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. – InTheSkies Mar 03 '14 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! (???) – aldo Mar 03 '14 at 20:04
  • 1
    @aldo because of the number of results for searching "python 3 print SyntaxError" here and elsewhere? – jonrsharpe Mar 03 '14 at 20:15

6 Answers6

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/

bgporter
  • 35,114
  • 8
  • 59
  • 65
  • 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. – InTheSkies Mar 03 '14 at 20:07
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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
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.

Community
  • 1
  • 1
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
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))
Balthazar Rouberol
  • 6,822
  • 2
  • 35
  • 41
0

In Python 3, print is a function

print(add(1,2))
print(addFixedValue(1))
Amit
  • 19,780
  • 6
  • 46
  • 54
0

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

shantanoo
  • 3,617
  • 1
  • 24
  • 37