3

I began learning Python a little time ago, and I got the first problem. Here's the code:

fh = open('/usr/share/dict/words')
for line in fh.readlines():
    print(line, end='')

When I execute it in the Terminal (OS X), it tells me invalid syntax error where end equal sign is placed. What's the problem here? Didn't find the solution...

I installed Python 3.3.0 from this page, Python 3.3.0 Mac OS X 64-bit/32-bit x86-64/i386 Installer

Sorry for so nooby questions :(

1
  • How are you running this code (like the command in Terminal)? It's being run with OS X's Python, not the one you installed. Commented Oct 6, 2012 at 7:44

2 Answers 2

6

Your terminal is probably using Python2.x

Try using the command python3 yourfilename.py

To see which Python version is the standard on your terminal just type python

You should see something like this:

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

To make your code work with 2.x you can use print without the parantheses:

print "Python", "yay!"
Sign up to request clarification or add additional context in comments.

2 Comments

Note you can't exactly replicate end='' on Python 2 (unless you use sys.stdout. A trailing comma will result in an extra space on the next output.
True, and why I changed the arguments. Shouldn't have glossed over it.
5

The Python 3 installer does not make Python 3 the default Python (if it did, it would break a ton of stuff, because very few Python scripts are Python 3 compatible). So to get Python 3, you should execute your script as python3 script.py, or add #!/usr/bin/env python3 to the top of the file.

5 Comments

If I had more votes left you'd get one. Did not know about the hashbang. Thanks.
It works with python3 script.py but how can I make Python 3 the default Python? Hashbang is not helping.
@Randex: You can modify PATH in your .profile script, or alias python=python3 (also in .profile). That way, you get Python 3 on the command line, but the system Python stays at Python 2 for compatibility.
So I just write python=python3 in it?
If you use alias, when you type python you'll get python 3, but scripts that use /usr/bin/env python will still get python 2, which is probably the best.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.