4

I don't know why i get the error because i have done exactly as the book says

>>> os.getcwd()
'C:\\Users\\expoperialed\\Desktop\\Pyt…'
>>> data = open('sketch.txt')
>>> print(data.readline(),end="")
SyntaxError: invalid syntax
8
  • What python version are you using? python --version Commented Aug 2, 2013 at 15:36
  • 5
    Check your Python version. Prior to Python 3, print wasn't a function, and this is the error 2.x gives if you try to call it like this. Commented Aug 2, 2013 at 15:36
  • what you REALLY want to do is to go download / install python 3.3 and never ever again use python 2. Also, upvoted the question :) Commented Aug 2, 2013 at 15:40
  • Yep, that's your problem then. As the answers say, either upgrade your Python or find a book or online tutorial that covers the older version if you need to use the older version. Commented Aug 2, 2013 at 15:40
  • 1
    @AnttiHaapala Too opinion based. In my opinion, Python 2.7 is much better than Python 3.3. Commented Aug 2, 2013 at 15:57

3 Answers 3

8

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

>>> from __future__ import print_function

That will need to be at the top of your Python program though because of the way the __future__ module works.

Sign up to request clarification or add additional context in comments.

Comments

6

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

print data.readline(),

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

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 would probably be to upgrade to Python 3.x. However, if you can't, then you might want to look at the __future__ module. It can make it so that you can use Python 3.x's print function in 2.x:

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

1 Comment

added the missing , (that is what the end='') does
2

It looks like you're running the wrong python version. There's currently 2 versions of Python running around, 2 and 3. In Python 2, print is a statement so you should change your code too

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

while in 3 it's a function and should be used how your book shows.

It looks like your book is in Python 3 so you should upgrade your python (For a beginner there's no reason not to use Python 3)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.