How do I fix this syntax error with print in Python? - python

I copied the Python code that Google Cloud recommends. I've tried it in Jupyter Notebook and as a Python file but I still get the syntax error:
def predict(content, project_id, model_id):
# More code.
pass
print predict("1.jpg", ispace-254720, ICN886814670746214838)
Gives:
File "<ipython-input-16-a9c7141e2bf3>", line 1
print predict("1.jpg", ispace-254720, ICN886814670746214838)
^
SyntaxError: invalid syntax

It's probably old Python 2.7 code. I'm guessing you're using Python 3, in which case print is now a function, so you need to put parentheses after print:
print(predict("1.jpg", ispace-254720, ICN886814670746214838))

Related

I'm trying to use imapgrab to imap gmail, but I can't because of the following error. imapgrab error DEBUG_000 [duplicate]

When I try to use a print statement in Python, it gives me this error:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: Missing parentheses in call to 'print'
What does that mean?
This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:
print "Hello, World!"
The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:
print("Hello, World!")
“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.
In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:
>>> print("Hello, World!")
Hello, World!
In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:
>>> print "Hello, World!"
File "<stdin>", line 1
print "Hello, World!"
^
SyntaxError: invalid syntax
As for why print became an ordinary function in Python 3, that didn't relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.
In Python 2:
>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6
In Python 3:
>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6
Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:
>>> print "Hello!"
File "<stdin>", line 1
print "Hello!"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?
Since the "Missing parentheses in call to print" case is a compile time syntax error and hence has access to the raw source code, it's able to include the full text on the rest of the line in the suggested replacement. However, it doesn't currently try to work out the appropriate quotes to place around that expression (that's not impossible, just sufficiently complicated that it hasn't been done).
The TypeError raised for the right shift operator has also been customised:
>>> print >> sys.stderr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?
Since this error is raised when the code runs, rather than when it is compiled, it doesn't have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it's straightforward to place quotes around the Python expression in the custom right shift error message.
Unfortunately, the old xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello, World!")
And someone has still to write that antigravity library :(
There is a change in syntax from Python 2 to Python 3.
In Python 2,
print "Hello, World!"
will work but in Python 3, use parentheses as
print("Hello, World!")
This is equivalent syntax to Scala and near to Java.
Basically, since Python 3.x you need to use print with parenthesis.
Python 2.x: print "Lord of the Rings"
Python 3.x: print("Lord of the Rings")
Explanation
print was a statement in 2.x, but it's a function in 3.x. Now, there are a number of good reasons for this.
With function format of Python 3.x, more flexibility comes when printing multiple items with comma separated.
You can't use argument splatting with a statement. In 3.x if you have a list of items that you want to print with a separator, you can do this:
>>> items = ['foo', 'bar', 'baz']
>>> print(*items, sep='+')
foo+bar+baz
You can't override a statement. If you want to change the behavior of print, you can do that when it's a function but not when it's a statement.
If your code should work in both Python 2 and 3, you can achieve this by loading this at the beginning of your program:
from __future__ import print_function # If code has to work in Python 2 and 3!
Then you can print in the Python 3 way:
print("python")
If you want to print something without creating a new line - you can do this:
for number in range(0, 10):
print(number, end=', ')
In Python 3, you can only print as:
print("STRING")
But in Python 2, the parentheses are not necessary.
I could also just add that I knew everything about the syntax change between Python2.7 and Python3, and my code was correctly written as print("string") and even
print(f"string")...
But after some time of debugging I realized that my bash script was calling python like:
python file_name.py
which had the effect of calling my python script by default using python2.7 which gave the error. So I changed my bash script to:
python3 file_name.py
which of coarse uses python3 to run the script which fixed the error.
print('Hello, World!')
You're using python 3, where you need brackets when printing.
Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.
As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).
So I was getting this error
from trp import BoundingBox, Document
File "C:\Users\Kshitij Agarwal\AppData\Roaming\Python\Python39\site-packages\trp\__init__.py", line 31
print ip
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(ip)?
This is a Python package error, in which Python2 has been used and you are probably running this on Python3.
One solution could be to convert Python2 print something to Python3 print(something) for every line in each file in the package folder, which is not a good idea😅. I mean, you can do it but still there are better ways.
To perform the same task, there is a package named 2to3 in Python which converts Python2 scripts to Python3 scripts. To install it, execute the 👇 command in terminal..
pip install 2to3
Then change the directory in terminal to the location where the package files are present, in my case - C:\Users\Kshitij Agarwal\AppData\Roaming\Python\Python39\site-packages\trp
Now execute the command 👇
2to3 . -w
and voila, all the Python2 files in that directory will be converted to Python3.
Note:- The above commands hold true for other operating systems as well. Only Python package path will vary as per the system.
print "text" is not the way of printing text in python as this won't work
print("text") will print said text on your screen in the command line

How to execute Python from NodeJS. Getting "invalid syntax" in my function from python

I'm using NodeJS to fire a Python script by way of python-shell package for the cozmo api.
The problem I'm having is when I execute my nodecozmo.py script from the command like it works perfectly. When I execute the exact same script from my node app, its giving me a syntax error when it executes the py.
Not sure how this could be a syntax error, maybe python-shell package somehow uses an older Python version? Maybe it doesn't understand handling that syntax? I tried to go through the source and couldn't see why its causing the issue.
Error
Error: File "nodecozmo.py", line 16
def cozmo_program(robot: cozmo.robot.Robot):
^
SyntaxError: invalid syntax
Python Script
import time
import cozmo
def cozmo_program(robot: cozmo.robot.Robot):
robot.move_head(-5)
time.sleep(3)
robot.drive_wheels(50, -50)
robot.move_lift(5)
time.sleep(3)
robot.move_lift(-1)
time.sleep(3)
cozmo.run_program(cozmo_program)
Node App
var PythonShell = require('python-shell');
PythonShell.run('./nodecozmo.py', function (err) {
if (err) throw err;
console.log('finished executing');
});
Your python script is using type hinting which is a new syntax introduced in Python 3.5. The def statement
def cozmo_program(robot: cozmo.robot.Robot):
is saying that the cozmo_program function takes one argument, robot, which should be of type cozmo.robot.Robot.
Since your script, nodecozmo.py, runs without errors from the command line, you must be running it with a version of Python >= 3.5.
Since NodeJS returns a SyntaxError, NodeJS must be running the script Python version < 3.5. Notice how the error message points directly at the colon:
Error: File "nodecozmo.py", line 16
def cozmo_program(robot: cozmo.robot.Robot):
^
SyntaxError: invalid syntax
Since type hinting is a nicety but not a necessity, you could make your script backwards compatible simply by removing the type hint:
Change
def cozmo_program(robot: cozmo.robot.Robot):
to
def cozmo_program(robot):

Syntax error only in python 3

I have the following code which runs fine on python 2 but throws error on python 3
import sys
if sys.version_info > (3,):
#print("Python 3")
#Try Block
except urllib2.HTTPError as err:
else:
#print "Python 2" # Throws error on python 3
#Try Block
except urllib2.HTTPError, err: # Throws error on python 3.
The above code returns "Python 2" in python 2, but throws syntax error on python 3 (For python 2 syntax ).
Can anyone tell me why is this happening ? And what is the work around to fix those syntax errors in python 3 ?
Note : I am aware of print syntax on Python 3
Thanks you!
The problem is that the parser runs before any code is evaluated at runtime. Your check sys.version_info > (3,) runs at run time, after the code was already parsed and compiled. So doing such checks, you are able to make changes at runtime, but that does not help you when dealing with syntax changes.
The syntax is parsed and compiled before any code is interpreted, that is why you get syntax errors even for code that is never run at runtime.
If you are trying to create a polyglot script that is able to run on both Python 3 and Python 2, then you will need to make sure to use a syntax that works on both. For print in particular, you can import the print function in Python 2, so you can use it just like you would in Python 3:
from __future__ import print_function
Some newer features won’t work that way (for example everything async), but for the most part, you can make it work somehow.
If you end up depending on stuff with Python 3 that requires Python 2-incompatible syntax, then you could put that into a separate module and import that module conditionally at runtime. That way it won’t be loaded for Python 2, so the Python 2 parser wouldn’t attempt to load the incompatible syntax.
As for why Python 2 does not throw an error, that’s actually very simple: print('foo bar') is valid syntax in Python 2, even with the print statement. That is because you can put parentheses around anything without impacting the value. So what you actually do there is this:
print ('foo bar')
^^^^^
print statement
^^^^^^^^^^^
value, wrapped in parentheses (that don’t do anything)
That’s also the reason, why the following produces different results in Python 3 and 2:
print('foo', 'bar')
In Python 3, you get foo bar as the output, while Python 2 gives you ('foo', 'bar'). That is because the comma inside the parentheses now makes this a tuple, so you pass a tuple to the print statement. – Importing the print function fixes this to give you the same behavior on Python 2 as on Python 3.
Even though the line print "Python 2" will never be executed in Python 3, it will still be compiled to byte code (or at least attempted). That line is a syntax error in Python 3, which requires the printed items to be in parentheses. Look up the documentation for more details: other changes to print were also made.
So remove the error. Make the line
print("Python 2") # Throws error on python 3
instead. That way it works in both Python 2 and in 3. There are many sites that discuss how to write code that executes in both versions of Python. The parentheses are merely ignored in version 2 but are needed in version 3. This works if you print only one item: more than one gets more complicated.
There is another way to do printing in both versions, using from __future__ import print_function but the way I showed is easier.
Note that your attempted comment in the line is also not proper Python syntax. Change the // to # and it works.

Invalid syntax in lapack testing file

When i compiled the LAPACK-3.4.2 with MinGW,i got a error like this:
File "./lapack_testing.py",line 17
**except getopt.error, msg:
^**
syntaxError:invalid syntax
Make:***[lapack_testing] Error 1
But i checked the lapack_testing.py,and there was no problem with the syntax.
Any idea?Thanks!
That exception handling syntax is valid in Python 2. Starting with Python 3 that syntax is no longer valid. Seep PEP 3110.
So it looks like the code you are running is designed for Python 2 but you are trying to execute it on Python 3. The expedient solution is going to be to run the code under Python 2, as it is intended to run.

Python - Different ways of printing?

I've installed PyDev into Eclipse, and when I do the print method in a .py file as print "Hello World" it didn't work. But then I did print ("Hello World") and it worked. I looked on the internet and everything says to do it without parentheses, but it doesn't work, and gives the error:
SyntaxError: invalid syntax
Would this be because I have an old or new version of python?
Any help would be appreciated.
You appear to be using Python 3.
In Python 2 print was a keyword and the parentheses were not required.
In Python 3 print was changed to be a function. When calling a function the parentheses are required.
Related
What's New in Python 3

Categories

Resources