Reputation: 635
I'm new to Python and I'm trying to declare a variable and print its value.
This is my code:
#!C:\Python32\python.exe
import sys
import os
import cgi
import cgitb
cgitb.enable()
a = 5
print(a)-------------------------> My doubt is in this line
But one of my friends writes that line as print a
. In his Python, it is printing that value, but in my case it is showing as "Invalid Syntax". Why is this happening?
Upvotes: 1
Views: 204
Reputation: 54312
Since you're in Python 3, print
is a function, so you call it as: print(a)
. In Python 2 (what your friend is using), you can leave off the parenthesis, and call it as just: print a
, but this won't work in the future, so your way is correct.
Also, your version (print(a)
) will work on both Python 3 and Python 2, since extra parenthesis are ignored as long as they match. I recommend always writing it in Python 3 style, since it works in both. You can make this explicit and required by using the (somewhat magical) __future__
module:
from __future__ import print_function
Having print
as a function causes some other differences, since in Python 3, you can set a variable to point to print
, or pass it as an argument to a function:
a = print
a('magic') # prints 'magic'
def add_and_call(func, num):
num += 1
func(num)
add_and_call(print, 1) # prints 2
Upvotes: 4
Reputation: 298532
In Python 2, print
isn't a function, but a keyword. The parentheses therefore don't matter and print 'foo'
works along with print('foo')
.
Python 3 made print
into a function, which has to be called with parameters: print('foo')
. Calling it as print 'foo'
will not work anymore.
Since you're getting errors when using print
as a keyword, you're using Python 3. You have to use print
as a function, just like you did. Your friend is using Python 2, which works both ways.
Python 3 and Python 2 are similar, but there are a few major differences that you should read about if you're planning on collaborating with someone who uses a different version of Python: http://docs.python.org/py3k/whatsnew/3.0.html
Upvotes: 5