Python SyntaxError when using end argument with print function

I don’t know why I get an error because I did exactly as the book says

>>> os.getcwd() 'C:\\Users\\expoperialed\\Desktop\\Pyt…' >>> data = open('sketch.txt') >>> print(data.readline(),end="") SyntaxError: invalid syntax 
+4
source share
3 answers

Or, to use the print function as you want in Python 2:

 >>> from __future__ import print_function 

This should be at the top of your Python program, though because of how the __future__ module __future__ .

+8
source

I think your problem is that you are on Python 2.x and using Python 3.x syntax. In Python 3.x, print is built-in and can be used like this. However, in 2.x it is a keyword and cannot. If you are on 2.x, do the following:

 print data.readline(), 

One way to see which version of Python you are using:

 import sys if sys.version_info.major == 2: # We are running 2.x elif sys.version_info.major == 3: # We are running 3.x 

or, from the terminal:

 $ python --version 

The best way to fix this problem is probably to upgrade to Python 3.x. However, if you cannot, you can look at the __future__ module. This can make it so that you can use the Python 3.x print function in 2.x:

 >>> from __future__ import print_function >>> print("yes!") yes! >>> print("a", "b", sep=",") a,b >>> 
+6
source

It looks like you are using the wrong version of python. There currently 2 versions of Python work around, 2 and 3. In Python 2, print is a statement, so you should also change your code

  print data.readline(), # The trailing comma to stop the newline 

while in 3 it is a function and should be used, as your book shows.

It looks like your book is in Python 3, so you should upgrade your python (for beginners there is no reason not to use Python 3)

+2
source

Source: https://habr.com/ru/post/1494985/


All Articles