Python - Different ways of printing? - python

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

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 do I fix this syntax error with print in 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))

print type(x) SyntaxError: invalid syntax [duplicate]

This question already has answers here:
Python 3 print without parenthesis
(10 answers)
Closed 4 years ago.
So I started learning python 3 and I wanted to run a very simple code on ubuntu:
print type("Hello World")
^
SyntaxError: invalid syntax
When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 instead of 3) then it's all fine. Same when using python 3 and 2 shells in the terminal.
It seems like I'm missing something really stupid because I did some research and found no one with the same issue.
In Python3, print was changed from a statement to a function (with brackets):
i.e.
# In Python 2.x
print type("Hello World")
# In Python 3.x
print(type("Hello World"))
In Python 3.x print() is a function, while in 2.x it was a statement. The correct syntax in Python 3 would be:
print(type("Hello World"))
This is because from Python 3, print is a function, not a statement anymore. Therefore, Python 3 only accepts:
print(type("Hello World"))

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.

Python SyntaxError? [duplicate]

This question already has answers here:
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?
(11 answers)
Closed 6 years ago.
I am learning a tutorial for Python language and trying to write a basic "Hello World!" program.
But when I do all steps described in the book I receive an error.
>> print "Hello World!"
SyntaxError: Missing parentheses in call to 'print'
Why I am getting this error?
Is my book wrong?
it seems that you're using Python 3.x.
In python 3.x, the print statement is a function and you need to use it as a function like this
print("Hello World!")
Your book is right, but might be outdated a bit. It seems it describes Python version 2, but you try to run your example on the version 3.
Python 3 has changed some features and this one is the most annoying to switch from P2 to P3.
"print" statement changed to function rather than operator as was in P2.
Calling function you should always use parentheses.
So, if you want to run your program in Python3 you should call it:
print("Hello World!")
And that's it.
If you want to use examples from your book as is - install Python2 and it should work.

Categories

Resources