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?
Since you’re in Python 3,
printis 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:Having
printas a function causes some other differences, since in Python 3, you can set a variable to point toprint, or pass it as an argument to a function: