1

I'm an experienced C++ developer, but am just getting my feet wet with Python for a project at work. I'm having some basic problems and Google has been less than helpful. I suspect something about my environment is funny, but I have no clue how to diagnose it. I wrote a simple script that merely prints an argument to the screen, but I am getting an error when running it (python args.py):

Syntax Error: invalid syntax
File "args.py", line 4
print arg0
     

For reference, there is a carrot underneath the 0 of arg0. The script in question:

import sys

firstArg = sys.argv[0]
print firstArg

I'm sure this is something really dumb, but Python is such a foreign thing, coming from C++.

2
  • 5
    What version of Python are you using? If it is Python 3.x, then you need to call print as a function: print(firstArg).
    – user2555451
    Apr 3, 2014 at 21:49
  • 1
    It's most likely 3 and you need print(firstArg).
    – dkasipovic
    Apr 3, 2014 at 21:50

2 Answers 2

4

This seems pretty obvious. The traceback says you have a SyntaxError on line 4, therefore print firstArg isn't valid Python.

The not obvious part is that a lot of examples on the Internet use syntax like that. This is because in Python 2.X versions, print was a statement. Since Python 3.0, print is a function. Try print(firstArg) instead.

Protip: If you want to enable the print function in Python 2, use from __future__ import print_function.

2
  • Thank you very much! None of the tutorials I was reading mentioned the syntax difference between Python 2.x and 3.x. I am using Python 3.2.3 at the moment.
    – jhammond
    Apr 3, 2014 at 22:06
  • Sadly, most of the Python community is still stuck on Python 2.X, due to dependencies not yet being ported. If at all possible, I recommend sticking with Python 3! Apr 3, 2014 at 22:21
1

I can understand that the print function of Python may be different for C or C++ developers because of its features. The syntax that you use is for python 2 (now in End Of Life status). There are many differences between Python 2 and python 3. In this case, the print was a statement in Python 2 but function in Python3. Here is the correct syntax for print function in Python3.

print(firstArg)

Brackets are important because print is a function. The print function in Python has some parameters which make it even more powerful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.