[Tutor] Running files from command prompt

Steven D'Aprano steve at pearwood.info
Fri Jul 29 07:27:26 CEST 2011


Alexander Quest wrote:
> To clarify, the particular file that was giving me trouble was the basic
> "hello world" file. The original code on line 29 read as such: print
> 'Hello', name
> When I ran "C:\google-python-exercises> python hello.py, it gave me an error
> on that line (line 29), but when I changed that line to print ('Hello',
> name), that is, including the parentheses, it printed out "hello world" as
> it should. I'm assuming that this means that one of the differences between
> Python 2.X and Python 3.X is that the print function necessitates
> parentheses in the latter versions but not in the former. 


Yes, that is correct.

To be a programmer (whether professional or amateur), you need to learn 
to *pay attention to the error given*. "It gave me an error" is 
meaningless. What does the error message say?

In this case, I expect it is a SyntaxError. But you need to learn to 
read the error message and understand what it is trying to tell you. 
Some errors are cryptic and don't help, but generally speaking Python is 
pretty good about giving useful error messages:


 >>> a = [1, 2, 3]
 >>> len a
   File "<stdin>", line 1
     len a
         ^
SyntaxError: invalid syntax


Admittedly you do need to learn that Python functions require 
parentheses, but apart from that, the error tells you what is wrong: you 
can't follow a function len with another name a without something 
between them. This is illegal syntax.



> I am a bit
> confused as to why this is, assuming I am correct in my assumption above,
> because I was under the impression that code written for earlier python
> versions will work for later python versions, as is the case here. 

Not quite. It is (mostly) true for Python 1.x and 2.x, but Python 3 has 
deliberately included some backwards incompatible changes. The biggest 
two are that strings are now Unicode rather than byte strings, and that 
print is now a function instead of a statement. So, yes, in Python 3 you 
have to call it with parentheses.

The differences are still quite minor -- think of Python 2.x and Python 
3.x being like the differences between American English and British 
English. Provided you pay attention to the error messages, and remember 
to add round brackets after print, tutorials for 2.x should still 
*mostly* work.


> I just wanted to add this info to clarify my last question regarding whether
> or not I should install Python 2.X and uninstall Python 3.1 that I have now,

Personally, I would consider it wiser to find a Python 3 tutorial. 
Python 3 is the future, and you will need to learn it eventually.




-- 
Steven


More information about the Tutor mailing list